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

前端 未结 30 2830
北恋
北恋 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:29

    The best solution (from 2019-2020) I found is that:

    function YouTubeGetID(url){
       url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
       return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
    }
    

    I found it here.

    /*
    * Tested URLs:
    var url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3';
    url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M';
    url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#';
    url = 'http://youtu.be/Ab25nviakcw';
    url = 'http://www.youtube.com/watch?v=Ab25nviakcw';
    url = '';
    url = '';
    url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg';
    url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit';
    url = 'BGL22PTIOAM';
    */
    

提交回复
热议问题