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));
|
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
12 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...