Get the YouTube video ID from a URL using JavaScript
Last Updated :
12 Jun, 2023
Given a YouTube Video URL, the task is to get the Video ID from the URL using JavaScript. Here are a few methods discussed.
JavaScript split() Method: This method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator, limit)
Parameters:
- separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)
- limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.
JavaScript String substring() Method: This method gets the characters from a string, between two defined indices, and returns the new substring. This method gets the characters in a string between “start” and “end”, excluding “end” itself.
Syntax:
string.substring(start, end)
Parameters:
- start: This parameter is required. It specifies the position from where to start the extraction. Index of first character starts from 0.
- end: This parameter is optional. It specifies the position (including) where to stop the extraction. If not used, it extracts the whole string.
Example 1: This example gets the Video ID by RegExp.
Javascript
let VID_REGEX =
/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
console.log(url.match(VID_REGEX)[1]);
|
Example 2: This example first splits the URL and then take a portion of the string by using split() and substring() method.
Javascript
console.log(url.split( "v=" )[1].substring(0, 11));
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...