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

How to Extract YouTube Video IDs from URLs Using Pure JavaScript?

Susan Sarandon
Release: 2024-11-30 08:34:14
Original
475 people have browsed it

How to Extract YouTube Video IDs from URLs Using Pure JavaScript?

How to Extract YouTube Video IDs from URLs in JavaScript

Identifying YouTube video IDs from their corresponding URLs is essential for various web development tasks. This question explores how to accomplish this using pure JavaScript, without relying on jQuery.

The provided examples showcase several URL formats commonly employed by YouTube to represent videos, including the "v=" parameter and others. The desired output is the 11-character video ID, such as "u8nQa1cJyX8" in the examples.

To address this challenge, the solution utilizes regular expressions. The enhanced version of the regular expression proposed by jeffreypriebe accommodates a broader range of YouTube URLs, including those that appear within YouTube channel pages.

function youtube_parser(url) {
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    var match = url.match(regExp);
    return (match && match[7].length == 11) ? match[7] : false;
}
Copy after login

This function supports a variety of YouTube URL formats, such as:

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
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
Copy after login

With this solution, developers have a reliable method for parsing YouTube URLs and extracting their corresponding video IDs in pure JavaScript. This capability proves particularly useful in scenarios where manipulating YouTube video content is necessary.

The above is the detailed content of How to Extract YouTube Video IDs from URLs Using Pure 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