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

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

    A slightly changed version from the one mantish posted:

    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]{11,11}).*/;
    var match = url.match(regExp);
    if (match) if (match.length >= 2) return match[2];
    // error
    

    This assumes the code is always 11 characters. I'm using this in ActionScript, not sure if {11,11} is supported in Javascript. Also added support for &v=.... (just in case)

提交回复
热议问题