Extracting YouTube Video Identifiers from URLs with JavaScript
Obtaining the unique video ID from a YouTube URL is a common task in web development. This ID allows you to access or manipulate videos from the YouTube platform via APIs or other means.
JavaScript Regex Solution
The most versatile method is using JavaScript regular expressions. The following enhanced regular expression from "jeffreypriebe" and "Javier Téllez" covers a wide range of YouTube URL formats:
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
Implementation
To use this regex, define a function:
function youtube_parser(url) { var match = url.match(regExp); return (match && match[7].length == 11) ? match[7] : false; }
Example
Example usage:
var videoId = youtube_parser("https://www.youtube.com/watch?v=fhWaJi15_fo"); console.log("Video ID:", videoId); // Output: fhWaJi15_fo
Compatibility
This regex method supports various YouTube URL formats including those with extra parameters and playlists:
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
The above is the detailed content of How Can I Extract YouTube Video IDs from URLs Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!