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\(?:/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\(?:/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="" 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.
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\.(?:/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\.(?:/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./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.
Share Improve this question edited May 25, 2012 at 9:44 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked May 25, 2012 at 9:40 Neil YoungNeil Young 55610 silver badges23 bronze badges 1- don't you think you should give credit to the answer owner on your blog? neilyoungcv./blog/code-share/… – Subliminal Hash Commented Jul 9, 2013 at 18:09
2 Answers
Reset to default 5You need to escape the /
slashes in your regex as they are the delimiter. Use \/
whenever you want to match a literal /
:
var reg = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g;
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:
var reg = new RegExp('(?:https?://)?(?:www\\.)?(?:youtu\\.be/|youtube\\.(?:/embed/|/v/|/watch\\?v=))([\\w-]{10,12})', 'g');
To get the ID eventually, use var id = reg.exec(yourString)[1]
.
You have to escape the forward slashes in your regular expression: \/
.