0

I just need to get the view code from youtube urls. The api is returning back strings that look like this:

http:\/\/www.youtube.com\/watch?v=XODUrTtvZks&feature=youtube_gdata_player

I need to get this part:

XODUrTtvZks

from the above, keep in mind that sometimes there may be additional parameters after the v=something like:

&feature=youtube_gdata_player

and sometimes there may not be. Can someone please provide the regex that would work in this situation and an example of how to use it using javascript?

  • 2
    You mean like this: http://www.rubular.com/r/gETdpfrVwc. You can look into Regular Expression for Javascript [here](http://www.w3schools.com/jsref/jsref_obj_regexp.asp). – mellamokb Oct 07 '11 at 15:35
  • mellamokb: You answer is correct. – Siva Charan Oct 07 '11 at 15:40
  • You may find [my answer to a very similar](http://stackoverflow.com/questions/5830387/php-regex-find-all-youtube-video-ids-in-string/5831191#5831191) question to be helpful. – ridgerunner Oct 08 '11 at 02:36

4 Answers4

1

You can use /v=([^&]+)/ and get the match at offset 1.

mck89
  • 18,918
  • 16
  • 89
  • 106
0

This snippet only matches on URL's from youtube.com:

var url = 'http://www.youtube.com/watch?v=XODUrTtvZks&feature=youtube_gdata_player';
var matches = url.match(/^http[s]?:\/\/www.youtube.com\/watch\?\s*v=([^&]+)/i);

if (matches) {
    var videoID = matches[1];
    // do stuff
}
fivedigit
  • 18,464
  • 6
  • 54
  • 58
0

You can use an online tool called RegExr to get your regular expression ,[http://gskinner.com/RegExr/].

Regards Rahul

Rahul
  • 1,549
  • 3
  • 17
  • 35
0

This snippet is from Google’s own parser at closure:

function getIdFromUrl(url) {
    return /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i.exec(url)[2];
}

You can see it here:

http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/ui/media/youtube.js?r=1221#246

David Hellsing
  • 106,495
  • 44
  • 176
  • 212