One of the common tasks when working with YouTube videos is extracting the video ID from the URL.
This can be useful for various purposes, such as embedding videos, retrieving video metadata, or building custom YouTube players.
Here's a simple JavaScript function that can help you extract the video ID from a YouTube URL:
function getYouTubeVideoId(url) {
// Define regular expressions to match different URL formats
const regexes = [
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/,
/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/,
/^.*youtube\.com\/shorts\/([^#\&\?]*).*/,
];
// Iterate through the regexes and try to match the URL
for (const regex of regexes) {
const match = url.match(regex);
if (match) {
if (match[7]) {
return match[7];
} else if (match[1]) {
return match[1];
}
}
}
// If no match is found, return null
return null;
}
console.log(getYouTubeVideoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ')); // Output: "dQw4w9WgXcQ"
console.log(getYouTubeVideoId('https://youtu.be/dQw4w9WgXcQ')); // Output: "dQw4w9WgXcQ"
console.log(getYouTubeVideoId('https://www.youtube.com/embed/dQw4w9WgXcQ')); // Output: "dQw4w9WgXcQ"
console.log(getYouTubeVideoId('https://www.youtube.com/v/dQw4w9WgXcQ?version=3&autohide=1')); // Output: "dQw4w9WgXcQ"
console.log(getYouTubeVideoId('https://www.youtube.com/shorts/dQw4w9WgXcQ')); // Output: "dQw4w9WgXcQ"
console.log(getYouTubeVideoId('https://example.com/not-a-youtube-url')); // Output: null