I have a PHP regular expression I’m using to get the YouTube video code out of a URL.
I’d love to match this with a client-side regular expression in JavaScript. Can anyone tell me how to convert the following PHP regex to JavaScript?
preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=embed/)[^&\n]+|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $url, $matches);
Much appreciated, thanks!
I think the only problem is to get rid of the lookbehind assertions
(?<=...), they are not supported in Javascript.The advantage of them is, you can use them to ensure that a pattern is before something, but they are NOT included in the match.
So, you need to remove them, means change
(?<=v=)[a-zA-Z0-9-]+(?=&)tov=[a-zA-Z0-9-]+(?=&), but now your match starts with “v=”.If you just need to validate and don’t need the matched part, then its fine, you are done.
But if you need the part after
v=then put instead the needed pattern into a capturing group and continue working with those captured values.You will then find the matched substring in $1 for the first group, $2 for the second, $3 …