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
Release: 2024-12-01 15:09:11
Original
163 people have browsed it

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?=?([^#&?]*).*/;
Copy after login

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;
}
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template