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

321,107

Solution 1

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
  video_id = video_id.substring(0, ampersandPosition);
}

Solution 2

I made an enhancement to Regex provided by "jeffreypriebe" because he needed a kind of YouTube URL is the URL of the videos when they are looking through a channel.

Well no but this is the function that I have armed.

<script type="text/javascript">
function youtube_parser(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    var match = url.match(regExp);
    return (match&&match[7].length==11)? match[7] : false;
}
</script>

These are the types of URLs supported

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

Can be found in [http://] http://lasnv.net/foro/839/Javascript_parsear_URL_de_YouTube

Solution 3

I simplified Lasnv's answer a bit.

It also fixes the bug that WebDeb describes.

Here it is:

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

Here is a regexer link to play with: http://regexr.com/3dnqv

Solution 4

None of these worked on the kitchen sink as of 1/1/2015, notably URLs without protocal http/s and with youtube-nocookie domain. So here's a modified version that works on all these various Youtube versions:

    // Just the regex. Output is in [1].
    /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/
    // For testing.
    var urls = [
        '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
        'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
        'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
        'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
        'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
        'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
        'http://youtu.be/6dwqZw0j_jY',
        'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
        'http://youtu.be/afa-5HQHiAs',
        'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
        'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
        'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
        'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
        'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
        'http://www.youtube.com/watch?v=peFZbP64dsU',
        'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
        'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
        'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
    ];
    var i, r, rx = /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/;
    for (i = 0; i < urls.length; ++i) {
        r = urls[i].match(rx);
        console.log(r[1]);
    }

Solution 5

/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/

Tested on:

  • 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/KdwsulMb8EQ
  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/v/dQw4w9WgXcQ
  • http://www.youtube.com/e/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • http://www.youtube.com/?v=dQw4w9WgXcQ
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
  • http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

Inspired by this other answer.

Share:
321,107

Related videos on Youtube

Adam Halasz
Author by

Adam Halasz

Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework

Updated on February 11, 2022

Comments

  • Adam Halasz
    Adam Halasz 10 months

    I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

    Example YouTube URL formats

    http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

    http://www.youtube.com/watch?v=u8nQa1cJyX8

    Or any other YouTube format that contains a video ID in the URL.

    Result from these formats

    u8nQa1cJyX8

  • Adam Halasz
    Adam Halasz over 12 years
    And what if the URL doesn't contains &?
  • karlphillip
    karlphillip over 12 years
    Then you must find what's the equivalent delimiter. For instance, the first URL you gave us its the & sign. On the second URL, the end of the string is the delimiter.
  • Gino about 10 years
    this is a usefull function to make it work where you want based on this code. var video_url = 'youtube.com/watch?v=eOrNdBpGMv8&feature=youtube_gdata'; ytid(video_url); function ytid(video_url) { var video_id = video_url.split('v=')[1]; var ampersandPosition = video_id.indexOf('&'); if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); } alert(video_id); return video_id; }​
  • Marc
    Marc almost 10 years
    ^.*(?:youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).* will give you the result in group 1
  • fabi
    fabi almost 9 years
    just a heads up: this should only be used when you know that you are dealing with a youtube url. I (wrongfully) used it to verify urls as youtube, which caused false positives, e.g. this passes: 'v/2059-9080-5437'
  • mantish
    mantish over 7 years
    I'm using now a different Regex that also checks for a youtube domain. I'm not sure if I should update the answer as it's a big change: /^.*(youtu.be\/|youtube(-nocookie)?.com\/(v\/|.*u\/\w\/|embe‌​d\/|.*v=))([\w-]{11}‌​).*/
  • Lenar Hoyt
    Lenar Hoyt about 7 years
    When will YouTube switch to 12 characters for the video ID?
  • Alex from Jitbit
    Alex from Jitbit about 7 years
    shouldn't the dot in "youtu.be" be escaped?
  • mantish
    mantish about 7 years
    you're right @jitbit Thank you. Although it usually works as well without escaping it.
  • alecellis1985
    alecellis1985 over 6 years
    not right, fails vs youtube.com/e/dQw4w9WgXcQ so please take out the efficient part :)
  • serge
    serge over 6 years
    does not handle embedded URLs
  • blented
    blented over 6 years
    Worth noting that many of the above solutions don't cover this wide batch of valid urls, the test script is very helpful, +1!
  • HopAlongPolly
    HopAlongPolly over 6 years
    Remove the double quotes from around the Regex pattern in the JavaScript code and it should work.
  • binaryfunt
    binaryfunt over 6 years
    Note that this will be fooled by something like "www.engadget.com/watch?v=dQw4w9WgXcQ", not that it's likely to be a problem though
  • Ashish
    Ashish over 6 years
    It works, but couldnt fixed the issue arising a text with multiple youtube url's See this regex101.com/r/qK5qJ5/1. It should not replace the second url.
  • Gino about 6 years
    I just find out that this regex will find a url with "tv" in it, even if it's not Youtube like: podtrac.com/pts/redirect.mp4/cdn.twit.tv/video/tnt/tnt1634/…
  • Gino about 6 years
    I changed this part |v\/| to |\?v\/|
  • podperson
    podperson over 5 years
    I'm not a fan of the overly permissive [^#\&\?]* — can't we use a slightly stricter \w or [a-zA-Z0-9_]{11,12} (to allow for 12-character ids some time in the future).
  • NickG
    NickG over 5 years
    @podperson Why would they switch to 12 char IDs? Its several billion years off before they run out of possible 11 char IDs.
  • NickG
    NickG over 5 years
    Nice idea, but it doesn't work on the vast majority of URL formats. Including not matching on any https sites.
  • podperson
    podperson over 5 years
    This solves the problems with the urls listed below by JW: /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\‌​?]*).*/
  • podperson
    podperson about 5 years
    @NickG I don't know what their schema for generating ids is. If it were merely based on unique numbers in base 62 or whatever they wouldn't need 11 character ids, would they? The larger point was that if you're expecting 11 characters of a particular type, put that in the search.
  • hamncheez
    hamncheez about 5 years
    also doesn't handle 'share' generated urls- https://youtu.be/{{video_id}}
  • zurfyx
    zurfyx about 5 years
    If you don't want that an empty ID matches: ^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?‌​\?v(?:i)?=|\&v(?:i)?‌​=))([^#\&\?]+).* (i.e. youtube.com/watch?v= will not match)
  • Brad
    Brad about 5 years
    There's no guarantee on the 11 character length.
  • brasofilo
    brasofilo almost 5 years
    This one is literally a duplicate of the accepted answer
  • Kerry Davis over 4 years
    with respect to when (if ever) youtube will go to 12 character VID's. I SUSPECT they may have chosen 11 because 11x5bits = 55 bits is the closest thing to the maximum JS integer size of 53 bits and the high order character will never use - or _. I could be totally wrong on this but if I'm not then they will stay at 11 until they want to jump to 22 or 24 (which could be the 12th of never). JUST AN OBSERVATION.
  • Chud37
    Chud37 about 3 years
    No one asked for python
  • Toto
    Toto almost 3 years
    Link only answer is useless, especially when it will be broken. Can you elaborate on this a little more?
  • Dipten
    Dipten almost 3 years
    This regex works well with youtube share and watch url. url='https://youtu.be/{{video_id}}'; url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|‌​be)(?:\/watch\?v=|\/‌​)([^\s&]+)/);
  • Maarten
    Maarten over 2 years
    I had issues with all other regex examples but this one effectively works on the 3 share options people on desktops use. an url from the address bar, an url from the share button and an url from the inline share button. Thanks!!!
  • Kamlesh
    Kamlesh about 2 years
    did not work for me. youtube.com/watch?v=a-XQJHpp5vI
  • garrettmaring
    garrettmaring almost 2 years
    This was very useful, thank you 🙏 The python regex from the pytube source is r"(?:v=|\/)([0-9A-Za-z_-]{11}).*"
  • MrMartiniMo
    MrMartiniMo over 1 year
    Thank you. I changed it a bit at the end: regex101.com/r/bTrei2/1
  • Dipo
    Dipo over 1 year
    @MrMartiniMo Thanks for the heads up but the regex in your link still doesn’t match YouTube IDs that contain hyphen (-). Example: youtube.com/watch?v=06w3-l1AzFk. I have updated my answer to match YouTube ID containing any character except the url delimiters.
  • tsdorsey
    tsdorsey about 1 year
    Good idea. I just updated the regex to remove the ^ entirely, it's not needed. I've also updated the regexr example as well. Thanks @AlexanderD'Attore
  • Jason about 1 year
    @rmutalik "everything but the kitchen sink" is an expression in English meaning "everything imaginable." In this case the author is making a reference to "all of the possible URLs."

Related