Home >Web Front-end >JS Tutorial >How Can I Extract a YouTube Video ID from its URL Using JavaScript?
Introduction:
Often, you may need to manipulate YouTube video URLs in your JavaScript code. A common requirement is obtaining the video's ID, the unique identifier used in the URL. This article will guide you through various methods to retrieve the YouTube video ID from a URL using plain JavaScript.
Method:
To parse the video ID from a YouTube URL, you can utilize the following regular expression:
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
This regular expression covers various YouTube URL formats, including:
Implementation:
To implement the method, define the following JavaScript function:
function getYouTubeVideoID(url) { var match = url.match(regExp); return match && match[7].length == 11 ? match[7] : false; }
This function takes a YouTube URL as input and returns the video ID if it successfully matches the regular expression. Otherwise, it returns false.
Example Usage:
var url = "http://www.youtube.com/watch?v=u8nQa1cJyX8"; var videoID = getYouTubeVideoID(url); console.log(videoID); // Output: "u8nQa1cJyX8"
Conclusion:
Using the provided JavaScript function, you can conveniently extract the YouTube video ID from a URL. This technique is useful when you need to manipulate or display the video ID in your applications.
The above is the detailed content of How Can I Extract a YouTube Video ID from its URL Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!