I am trying to port over a PHP preg_match expression to pull a video ID from YouTube embed code in Javascript. I currently have this in PHP:
$pattern = '%(?:https?://)?(?:www\.)?(?:youtu\.be/| youtube\.com(?:/embed/|/v/|/watch\?v=))([\w-]{10,12})[a-zA-Z0-9\<\>\"]%x';
$result = preg_match($pattern, $url, $matches);
This works and returns me a video id. I have tried using the following in order to get it to work in Javascript:
var reg = /(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=))([\w-]{10,12})/g;
var matches = uploadVideoEmbedCode.match(reg);
The test data I am using is:
<iframe width="560" height="315" src="http://www.youtube.com/embed/1NMUDb3Ewhs" frameborder="0" allowfullscreen></iframe>
When I try and use the above regular expression in javascript I get the following error:
Uncaught SyntaxError: Unexpected token ?
You help as ever would be greatly appreciated.
You need to escape the
/slashes in your regex as they are the delimiter. Use\/whenever you want to match a literal/:Another option would be using
new RegExp('...', 'g')instead of/.../g– but then you need to escape each backslash which would be even more annoying:To get the ID eventually, use
var id = reg.exec(yourString)[1].