Problem:
Obtain the video ID (e.g., "u8nQa1cJyX8") from a given YouTube URL in JavaScript.
Enhanced Regular Expression:
To account for various YouTube URL formats, here is an enhanced regular expression:
function youtube_parser(url) { var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/; var match = url.match(regExp); return (match && match[7].length == 11) ? match[7] : false; }
This expression supports the following URL formats:
Example:
var url = 'https://www.youtube.com/watch?v=u8nQa1cJyX8'; var videoId = youtube_parser(url); console.log(videoId); // Output: u8nQa1cJyX8
The above is the detailed content of How to Extract a YouTube Video ID from its URL Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!