1

Possible Duplicate:
Regex to parse youtube yid

your probably thinking not another one, but here i have a jquery regex which i find it works fine on the majority of urls accpet one example at bottom:

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

the regex

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

but this cannot extract the id from the url below (in this example the id is pa14VNsdSYM)

http://www.youtube.com/watch?feature=endscreen&NR=1&v=pa14VNsdSYM

how can using the regex can i extract the id from urls such as the one above.

Community
  • 1
  • 1
Yusaf Khaliq
  • 3,333
  • 11
  • 42
  • 82
  • Have you tried using the regex as it's written in the question I linked to? – Mark Biek Dec 05 '11 at 16:16
  • The regexp at the link provided by Mark doesn't allow for `_` in the id, which is why it doesn't work for the given videos. I made a comment on his answer. – Kevin B Dec 05 '11 at 17:23
  • See also [my answer](http://stackoverflow.com/a/5831191/433790) to another very similar question. – ridgerunner Dec 05 '11 at 20:12
  • Related: http://stackoverflow.com/questions/2936467/parse-youtube-video-id-using-preg-match/6382259#6382259 – Timo Huovinen Mar 12 '14 at 11:33

1 Answers1

9

The youtube url id always contains 11 characters numbers underscores and/or dashes. This is the regexp i've used and haven't had issues with:

var re = /[a-zA-Z0-9\-\_]{11}/;
var youtubeurl = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";
alert(youtubeurl.match(re));

Edit: this solution doesn't actually work 100%, the first and second url's will have issues because the regexp matches text that isn't the vid id.

Edit2: try this one:

var re = /(\?v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var urlArr = [
    "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"                  
];
for (var i = 0; i < urlArr.length; i++) {
    alert(urlArr[i].match(re)[2]);
}

http://jsfiddle.net/HfqmE/1/

Kevin B
  • 94,570
  • 16
  • 163
  • 180