0

I'm trying to use this great RegEx presented here for grabbing a video id from any youtube type url:

parse youtube video id using preg_match

// getting our youtube url from an input field.
var yt_url = $('#yt_url').val();

var regexp = new RegExp('%(?:youtube(?:-nocookie)?\\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\\.be/)([^"&?/ ]{11})%','i');
var videoId = yt_url.match( regexp ) ;

console.log('vid: '+videoId);

My console is always giving me a null videoId though. Am I incorrectly escaping something in my regexp var? I added the a second backslash to escape the single backslashes already.

Scratching my head?

Community
  • 1
  • 1
skålfyfan
  • 4,931
  • 5
  • 41
  • 59

1 Answers1

0

% are delimiters for the PHP you got the link from, Javascript does not expect delimiters when using new RegExp(). Also, it looks like \\. should probably be replaced with \. Try:

var regexp = new RegExp('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})','i');

Also, you can create a regular expression literally by using Javascript's /.../ delimiters, but then you'll need to escape all of your /s:

var regexp = /(?:youtube(?:-nocookie)?\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\\.be\/)([^"&?\/ ]{11})/i;

Documentation


Update:

A quick update to address the comment on efficiency for literal expressions (/ab+c/) vs. constructors (new RegExp("ab+c")). The documentation says:

Regular expression literals provide compilation of the regular expression when the script is loaded. When the regular expression will remain constant, use this for better performance.

And:

Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Since your expression will always be static, I would say creating it literally (the second example) would be slightly faster since it is compiled when loaded (however, don't confuse this into thinking it won't be creating a RegExp object). This small difference is confirmed with a quick benchmark test.

Sam
  • 20,096
  • 2
  • 45
  • 71
  • If that doesn't work for you, update your OP with an example URL (`$('#yt_url').val()`) and I can check the expression's logic..however the `%` is definitely causing issues. – Sam May 23 '14 at 20:11
  • awesome. both worked. Is the second version any more efficient than the first since we're not creating a RegExp obj? – skålfyfan May 23 '14 at 20:19