Skip to content

Instantly share code, notes, and snippets.

@takien
Last active April 13, 2024 16:19
Show Gist options
  • Save takien/4077195 to your computer and use it in GitHub Desktop.
Save takien/4077195 to your computer and use it in GitHub Desktop.
Get YouTube ID from various YouTube URL using JavaScript
/**
* Get YouTube ID from various YouTube URL
* @author: takien
* @url: http://takien.com
* For PHP YouTube parser, go here http://takien.com/864
*/
function YouTubeGetID(url){
var ID = '';
url = url.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if(url[2] !== undefined) {
ID = url[2].split(/[^0-9a-z_\-]/i);
ID = ID[0];
}
else {
ID = url;
}
return ID;
}
/*
* Tested URLs:
var url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3';
url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M';
url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#';
url = 'http://youtu.be/Ab25nviakcw';
url = 'http://www.youtube.com/watch?v=Ab25nviakcw';
url = '<iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>';
url = '<object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg';
url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit';
url = 'BGL22PTIOAM';
*/
@jtewright
Copy link

👍

@ronitonit
Copy link

@RyanCasas
Copy link

RyanCasas commented Aug 24, 2017

I added @ronitonit URLs to @csepulveda-xumak 's version:

function YouTubeGetID(url){
    url = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return undefined !== url[2]?url[2].split(/[^0-9a-z_\-]/i)[0]:url[0];
}

@andrewarosario
Copy link

Great! Thank you so much!

@Joshfindit
Copy link

Please test the following:

https://www.youtube.com/red
https://www.youtube.com/channel/UCEgdi0XIXXZ-qJOFPf4JSKw

Currently, they match successfully and return a bad Video ID

@mvww11
Copy link

mvww11 commented Mar 31, 2018

Thanks!!

YouTubeGetID('http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw123123#');
returns a string.

YouTubeGetID('Ab25nviakcw123123');
returns an array.

To make the last one returns a string too, just replate ID = url; for ID = url[0]; in the else clause

@Soullighter
Copy link

Soullighter commented Jun 19, 2018

For PHP YouTube parser, go here http://takien.com/864

The URL does not exist, can you provide a new one?

@banada
Copy link

banada commented Jul 13, 2018

This is great! Can I use this in my project? There is no license right now.

@JetmirAhmati
Copy link

JetmirAhmati commented Aug 29, 2018

hi all,
I tested here with these url and seems that is not working
https://www.youtube-nocookie.com/embed//5ybGYHlgNGo
Could somebody help ?

@vuice
Copy link

vuice commented Nov 29, 2018

hi all,
I tested here with these url and seems that is not working
https://www.youtube-nocookie.com/embed//5ybGYHlgNGo
Could somebody help ?

Just in case you haven't figured it out yet, you have 2 "/" after "embed", making the string invalid.

@kangfarih
Copy link

Thank you so much,..

@EylonSu
Copy link

EylonSu commented May 30, 2019

Thanks!

@burnoutprojects
Copy link

burnoutprojects commented Dec 5, 2019

A quick fix for that kind of links https://www.youtube-nocookie.com/embed//5ybGYHlgNGo /(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/\/?)/

@JoshuaFrontEnd
Copy link

Thanks!! 👏

@avag01
Copy link

avag01 commented Dec 20, 2019

Thanks!

@wenogk
Copy link

wenogk commented Dec 28, 2019

Amazing.

@katai5plate
Copy link

Great!

TypeScript:

const youTubeGetID = (url: string) => {
  const [a, , b] = url
    .replace(/(>|<)/gi, '')
    .split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
  if (b !== undefined) {
    return b.split(/[^0-9a-z_-]/i)[0];
  } else {
    return a;
  }
};

@btroncone
Copy link

Thanks for the TypeScript version, works perfectly!

@raziEiL
Copy link

raziEiL commented Aug 9, 2020

I added @ronitonit URLs to @csepulveda-xumak 's version:

function YouTubeGetID(url){
    url = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return undefined !== url[2]?url[2].split(/[^0-9a-z_\-]/i)[0]:url[0];
}

Optimized typescript version (immutable, camelCase style)

function getYouTubeId(url: string) {
    const arr = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return undefined !== arr[2] ? arr[2].split(/[^\w-]/i)[0] : arr[0];
}

@willowell
Copy link

I added @ronitonit URLs to @csepulveda-xumak 's version:

function YouTubeGetID(url){
    url = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return undefined !== url[2]?url[2].split(/[^0-9a-z_\-]/i)[0]:url[0];
}

Optimized typescript version (immutable, camelCase style)

function getYouTubeId(url: string) {
    const arr = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return undefined !== arr[2] ? arr[2].split(/[^\w-]/i)[0] : arr[0];
}

Hello! May I use this function in a website I'm working on?

@yannicka
Copy link

PHP equivalent:

function extractYoutubeVideoCode(string $url): ?string
{
    $matches = preg_split('/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/', $url);

    if (!isset($matches[1])) {
        return null;
    }

    $match = $matches[1];
    $split = preg_split('/[^\w-]/i', $match);

    if (!isset($split[0])) {
        return null;
    }

    return $split[0];
}

@nasirDoe
Copy link

nasirDoe commented Mar 8, 2021

Thankyou brad

@vitorjustin
Copy link

Thanks!

@mikepenski
Copy link

Thanks!

@inscapist
Copy link

inscapist commented Jul 22, 2021

Thanks! here is my clojurescript equivalent (in #"" regex literal)

(defn parse-youtube [url]
  (let [host-re #"(vi/|v=|/v/|youtu.be/|/embed/)"
        key-re #"(?i)[^0-9a-z_-]"
        parts (str/split url host-re)]
    (if (< (count parts) 2)
      (parts 0)
      ((str/split (parts 2) key-re) 0))))

(comment
  (let [examples ["https://music.youtube.com/watch?v=6qg4EuEjDuQ"
                  "http://youtu.be/Ab25nviakcw"
                  "https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M"
                  "http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg"
                  "BGL22PTIOAM"]]
    (map parse-youtube examples)))

@bilalbhojani24
Copy link

It works for all the cases. +1!! Thanks @takien

@shlomisas
Copy link

The code has unexpected results when i provide it with a link that is not one of the valid youtube domains, e.g. the link https://ssssssssss?v=OoY9gyXTuD8 return OoY9gyXTuD8 which is not correct. FYI.

@MateusAuri
Copy link

might wanna add a |\/shorts\/| to the split regex to catch the newer format too, e.g. https://www.youtube.com/shorts/RGoMN6my_JA

@adam-sas-on
Copy link

I found a better RegExp which includes YouTube shorts also:
/^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/

Try to check these use-cases by e.g. JEST:

let urls = [
    {test: 'https://www.youtube.com/shorts/5r7QeUnpLKE?feature=share', expected: "5r7QeUnpLKE"},
    {test: '//www.youtube-nocookie.com/embed/sTu3LwpF6XI?rel=0', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/watch?v=sTu3LwpF6XI&feature=channel', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/watch?v=wnxMg4Urro8&playnext_from=TL&videos=osPknwzXEas&feature=sub', expected: 'wnxMg4Urro8'},
    {test: 'https://www.youtube.com/ytscreeningroom?v=wnxMg4Urro8', expected: 'wnxMg4Urro8'},
    {test: 'https://www.youtube.com/user/AnnafromUkrainej#p/a/u/2/g-Z_hxmynIM', expected: 'g-Z_hxmynIM'},
    {test: 'https://youtu.be/sTu3LwpF6XI', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/watch?v=sTu3LwpF6XI&feature=youtu.be', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtu.be/sTu3LwpF6XI', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo', expected: '1p3vcRhsYGo'},
    {test: 'https://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0', expected: '1p3vcRhsYGo'},
    {test: 'https://www.youtube.com/watch?v=sTu3LwpF6XI&playnext_from=TL&videos=osPknwzXEas&feature=sub', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/embed/5r7QeUnpLKE?rel=0', expected: '5r7QeUnpLKE'},
    {test: 'https://www.youtube.com/watch?v=JYYajVARdZ0', expected: 'JYYajVARdZ0'},
    {test: 'https://youtube.com/v/sTu3LwpF6XI?feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtube.com/vi/sTu3LwpF6XI?feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtube.com/?v=sTu3LwpF6XI&feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://www.youtube.com/watch?v=sTu3LwpF6XI&feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtube.com/?vi=sTu3LwpF6XI&feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtube.com/watch?v=sTu3LwpF6XI&feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtube.com/watch?vi=sTu3LwpF6XI&feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: 'https://youtu.be/sTu3LwpF6XI?feature=youtube_gdata_player', expected: 'sTu3LwpF6XI'},
    {test: "https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router", expected: "" /* (*) */},
    {test: "https://gist.github.com/takien/4077195", expected: "" /* (*) */}
];

let i = 0;
test('Test for ' + urls[i], ()={
    let youTubeId = YouTubeGetID(urls[i].test);
    expect(youTubeId).toBe(urls[i].expected);
});

/* (*) "" or false or undefined ...  */

Thanks for your work for my first try
🙂

@temp3l
Copy link

temp3l commented Dec 31, 2023

worked best for me (in typescript):

export const youTubeGetID = (url: string) => {
    const [a, , b] = url.replace(/(>|<)/gi, '').split(/^.*(?:(?:youtu\.?be(\.com)?\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/)
    if (b !== undefined) {
        return b.split(/[^0-9a-z_-]/i)[0]
    } else {
        return a
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment