Home >Web Front-end >JS Tutorial >How Can I Extract a YouTube Video ID from its URL Using JavaScript?

How Can I Extract a YouTube Video ID from its URL Using JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-01 15:09:11157browse

How Can I Extract a YouTube Video ID from its URL Using JavaScript?

How to Extract YouTube Video ID from 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:

  • http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
  • http://www.youtube.com/watch?v=u8nQa1cJyX8
  • http://youtu.be/u8nQa1cJyX8

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn