Search code examples
javascriptjqueryyoutube

how to get youtube video id from url


I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.

I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.

I need something that matches all these URL's:

http(s)://www.youtu.be/videoID

http(s)://www.youtube.com/watch?v=videoID

(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)

Any ideas which can be handled by the browser quick/efficient is greatly appreciated!


Solution

  • Try this:

    var url = "...";
    var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
    if(videoid != null) {
       console.log("video id = ",videoid[1]);
    } else { 
        console.log("The youtube url is not valid.");
    }
    

    see regex:

    /
    (?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
    (?:w{3}\.)?      // Optional sub-domain, if have, must be www.
    youtu(?:be)?  // The domain. Match 'youtu' and optionally 'be'. 
    \.(?:com|be) // the domain-extension must be .com or .be
    (?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
    /