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

前端 未结 30 3036
北恋
北恋 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条回答
  •  猫巷女王i
    2020-11-22 03:31

    This definitely requires regex:

    Copy into Ruby IRB:

    var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
    var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
    url.match(VID_REGEX)[1]
    

    See for all test cases: https://gist.github.com/blairanderson/b264a15a8faaac9c6318

提交回复
热议问题