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

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

    tl;dr.

    Matches all URL examples on this question and then some.

    let re = /^(https?:\/\/)?((www\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)/i;
    let id = "https://www.youtube.com/watch?v=l-gQLqv9f4o".match(re)[7];
    

    ID will always be in match group 7.

    Live examples of all the URLs I grabbed from the answers to this question: https://regexr.com/3u0d4

    Full explanation:

    As many answers/comments have brought up, there are many formats for youtube video URLs. Even multiple TLDs where they can appear to be "hosted".

    You can look at the full list of variations I checked against by following the regexr link above.

    Lets break down the RegExp.

    ^ Lock the string to the start of the string. (https?:\/\/)? Optional protocols http:// or https:// The ? makes the preceding item optional so the s and then the entire group (anything enclosed in a set of parenthesis) are optional.

    Ok, this next part is the meat of it. Basically we have two options, the various versions of www.youtube.com/...[id] and the link shortened youtu.be/[id] version.

    (                                                  // Start a group which will match everything after the protocol and up to just before the video id.
      (www\.)?                                         // Optional www.
      (youtube(-nocookie)?|youtube.googleapis)         // There are three domains where youtube videos can be accessed. This matches them.
      \.com                                            // The .com at the end of the domain. 
      .*                                               // Match anything 
      (v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/) // These are all the things that can come right before the video id. The | character means OR so the first one in the "list" matches.
      |                                                // There is one more domain where you can get to youtube, it's the link shortening url which is just followed by the video id. This OR separates all the stuff in this group and the link shortening url.
      youtu\.be\/                                      // The link shortening domain
    )                                                  // End of group
    

    Finally we have the group to select the video ID. At least one character that is a number, letter, underscore, or dash.

    ([_0-9a-z-]+)
    

    You can find out much more detail about each part of the regex by heading over the regexr link and seeing how each part of the expression matches with the text in the url.

提交回复
热议问题