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

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

    Given that YouTube has a variety of URL styles, I think Regex is a better solution. Here is my Regex:

    ^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*
    

    Group 3 has your YouTube ID

    Sample YouTube URLs (currently, including "legacy embed URL style") - the above Regex works on all of them:

    http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
    http://www.youtube.com/embed/0zM3nApSvMg?rel=0
    http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
    http://www.youtube.com/watch?v=0zM3nApSvMg
    http://youtu.be/0zM3nApSvMg
    http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
    http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
    

    Hat tip to Lasnv

提交回复
热议问题