JAVASCRIPT

Extract YouTube Video ID from URL

Quickly extract the unique video ID from various YouTube URL formats (watch, embed, short, youtu.be) using a robust regex pattern.

function getYouTubeVideoId(url) {
    const regex = /(?:https?:\/\/)?(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=|embed\/|v\/|shorts\/)?([\w-]{11})(?:\S+)?/i;
    const match = url.match(regex);
    return match ? match[1] : null;
}

// Example usage:
// console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'));
// console.log(getYouTubeVideoId('https://youtu.be/dQw4w9WgXcQ'));
// console.log(getYouTubeVideoId('https://www.youtube.com/embed/dQw4w9WgXcQ'));
// console.log(getYouTubeVideoId('https://www.youtube.com/shorts/dQw4w9WgXcQ'));
How it works: This JavaScript function extracts the 11-character video ID from various YouTube URL formats, including 'watch', 'embed', 'v', 'shorts', and 'youtu.be' links. The regular expression accounts for optional 'https://', 'www.', and 'm.' prefixes. It captures the alphanumeric ID using a specific group `([\w-]{11})`. If a valid YouTube URL is provided and matches the pattern, the function returns the captured video ID; otherwise, it returns `null`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs