Extracting Video ID from YouTube URL with JavaScript
Extracting a video ID from a YouTube URL is a common task when you want to manipulate or display videos in your web application. How to create a simple JavaScript function that can extract the YouTube video ID from various URL formats.
YouTubeGetID
Function
The YouTubeGetID
function we will create uses string splitting and regular expressions to extract the video ID from a YouTube URL. Here is the function code:
function YouTubeGetID(url) {
// Split the URL using different delimiters
url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
// Check if the video ID is found and return it
return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}
Code Explanation
-
Splitting the URL:
url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
- This code uses the
split
function with a regular expression to split the URL based on several common patterns for YouTube video IDs. These patterns include:vi/
- Used in certain URL formatsv=
- A common query parameter/v/
- Used in some URL formatsyoutu.be/
- Short URL format/embed/
- Used in embed URLs
- This code uses the
-
Extracting the Video ID:
return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
- After splitting, the video ID is typically located at the second index of the split result array (
url[2]
). If found, the ID is extracted by splitting the string based on non-alphanumeric characters and special characters. - If
url[2]
does not exist (e.g., the URL does not match the expected pattern),url[0]
(which is the first part of the split result array) is returned.
- After splitting, the video ID is typically located at the second index of the split result array (
Example Usage
Here are some examples of how this function is used to get the video ID from different YouTube URLs:
console.log(YouTubeGetID('https://www.youtube.com/watch?v=QOM0xWASUwE'));
// Output: QOM0xWASUwE
console.log(YouTubeGetID('https://youtu.be/QOM0xWASUwE'));
// Output: QOM0xWASUwE
console.log(YouTubeGetID('https://www.youtube.com/embed/QOM0xWASUwE'));
// Output: QOM0xWASUwE
console.log(YouTubeGetID('https://www.youtube.com/vi/QOM0xWASUwE'));
// Output: QOM0xWASUwE
Conclusion
The YouTubeGetID
function is a useful tool for extracting video IDs from YouTube URLs in various formats. By using string splitting and regular expressions, you can easily retrieve the necessary video ID for displaying or manipulating videos in your web application. Make sure to test this function with different URL formats to ensure comprehensive coverage.