YouTube Video ID in JS
Extract 11-character YouTube video IDs from long URLs, short URLs, or embed URLs.
Try it in the JS tester →Pattern
regexJS
(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([\w\-]{11}) (flags: g)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("(?:youtube\\.com\\/watch\\?v=|youtu\\.be\\/|youtube\\.com\\/embed\\/)([\\w\\-]{11})", "g");
const input = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
Matches any of three URL forms (watch?v=, youtu.be/, embed/) and captures the 11-character video ID that follows. The ID uses word characters and hyphens.
Examples
Input
https://www.youtube.com/watch?v=dQw4w9WgXcQMatches
youtube.com/watch?v=dQw4w9WgXcQ
Input
https://youtu.be/dQw4w9WgXcQMatches
youtu.be/dQw4w9WgXcQ
Input
not a youtube urlNo match
—