JAVASCRIPT
Extract YouTube Video ID from URLs
Easily extract the unique video ID from standard, shortened, and embed YouTube URLs using a single, versatile regular expression.
function getYouTubeVideoId(url) {
// This regex captures the 11-character YouTube video ID from various URL formats:
// Standard: https://www.youtube.com/watch?v=VIDEO_ID
// Shortened: https://youtu.be/VIDEO_ID
// Embed: https://www.youtube.com/embed/VIDEO_ID
// V: https://www.youtube.com/v/VIDEO_ID
const youtubeRegex = /(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|)([\w-]{11})(?:\S+)?/;
const match = url.match(youtubeRegex);
return match ? match[1] : null;
}
// Examples:
// console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ')); // dQw4w9WgXcQ
// console.log(getYouTubeVideoId('https://youtu.be/dQw4w9WgXcQ')); // dQw4w9WgXcQ
// console.log(getYouTubeVideoId('http://www.youtube.com/embed/dQw4w9WgXcQ')); // dQw4w9WgXcQ
// console.log(getYouTubeVideoId('https://www.youtube.com/v/dQw4w9WgXcQ?fs=1')); // dQw4w9WgXcQ
// console.log(getYouTubeVideoId('not-a-youtube-url')); // null
How it works: The `getYouTubeVideoId` function extracts the 11-character unique ID from various YouTube URL formats. The regular expression `(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|)([\w-]{11})(?:\S+)?` uses non-capturing groups (`?:...`) to match optional protocol, subdomains, and different YouTube hostnames or path segments. The core video ID is captured by `([\w-]{11})`, which matches exactly 11 word characters or hyphens, representing the unique video identifier.