Skip to content

Instantly share code, notes, and snippets.

@takien
Last active May 3, 2024 12:41
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';
*/
@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