Home > Web Front-end > JS Tutorial > How Can I Extract YouTube Video IDs from URLs Using JavaScript?

How Can I Extract YouTube Video IDs from URLs Using JavaScript?

DDD
Release: 2024-11-30 08:20:15
Original
671 people have browsed it

How Can I Extract YouTube Video IDs from URLs Using JavaScript?

Extracting YouTube Video Identifiers from URLs with JavaScript

Obtaining the unique video ID from a YouTube URL is a common task in web development. This ID allows you to access or manipulate videos from the YouTube platform via APIs or other means.

JavaScript Regex Solution

The most versatile method is using JavaScript regular expressions. The following enhanced regular expression from "jeffreypriebe" and "Javier Téllez" covers a wide range of YouTube URL formats:

var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
Copy after login

Implementation

To use this regex, define a function:

function youtube_parser(url) {
    var match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : false;
}
Copy after login

Example

Example usage:

var videoId = youtube_parser("https://www.youtube.com/watch?v=fhWaJi15_fo");
console.log("Video ID:", videoId); // Output: fhWaJi15_fo
Copy after login

Compatibility

This regex method supports various YouTube URL formats including those with extra parameters and playlists:

http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
Copy after login

The above is the detailed content of How Can I Extract YouTube Video IDs from URLs 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template