1

I need a function that can get the video ID from both Vimeo and YouTube urls.

I have done some digging and found these urls:

https://vimeo.com/30466080 
https://vimeo.com/30466080#t=0 
http://www.youtube.com/watch?feature=player_detailpage&v=My2FRPA3Gf8 http://www.youtube.com/watch?v=My2FRPA3Gf8 
//www.youtube.com/v/My2FRPA3Gf8?version=3&hl=en_GB 
//www.youtube-nocookie.com/v/My2FRPA3Gf8?version=3&hl=en_GB //www.youtube.com/embed/My2FRPA3Gf8

Vimeo, really only has one kind and is always in the same position.

YouTube however is safe to say that their 64bit id algorithm won't be changing anytime soon, so the 11 character count it safe to assume always.

I'm wondering what's the best way to tackle this rather than chaining 6 or 7 different if commands?

Shannon

Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95

3 Answers3

1

See JavaScript REGEX: How do I get the YouTube video id from a URL?

Assuming url is a variable holding the youtube video url as a string:

url.match(/.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/)[1]
Community
  • 1
  • 1
dajavax
  • 3,060
  • 1
  • 14
  • 14
  • Thankyou for the link, you've helped me narrow down my searches, here's what I came up with: http://jsfiddle.net/shannonhochkins/f94Dv/ – Shannon Hochkins Sep 19 '13 at 03:50
1

This is kinda ugly, but it catches all the above examples:

  function videoID(url) {
    return url.replace(/\\/g,'/').replace( /.*\//, '').replace(/#.*/, '').replace(/(.*\?v=|\?version=.*)/, '');
  }
Shylo Hana
  • 1,792
  • 13
  • 10
0

You can try using the Regular expression used in the link that FaceOfJock provided and then apply it using the JavaScript RegExp Object:

http://www.w3schools.com/jsref/jsref_obj_regexp.asp

axy108
  • 537
  • 2
  • 4
  • 14