How do I get the YouTube video ID from a URL?

前端 未结 30 3016
北恋
北恋 2020-11-22 03:06

I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

Example YouTube URL formats

http://www.youtube.c

30条回答
  •  情书的邮戳
    2020-11-22 03:45

    I made a small function to extract the video id out of a Youtube url which can be seen below.

    var videoId = function(url) {
       var match = url.match(/v=([0-9a-z_-]{1,20})/i);
       return (match ? match['1'] : false);
    };
    
    console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'));
    console.log(videoId('https://www.youtube.com/watch?t=17s&v=dQw4w9WgXcQ'));
    console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=17s'));

    This function will extract the video id even if there are multiple parameters in the url.

提交回复
热议问题