Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex return capture group value

I am parsing a youtube URL and I want to get the video id but I'm having such a hard time

The only way I could come up with is this

href = 'https://www.youtube.com/watch?v=-UI86rRSHkg'

...

video = href.replace(/^.*?youtube\.com\/.*?v=(.+?)(?:&|$).*/i, '$1');

But I think there must be a better way to do this.

How can I get the value of a capture group in JavaScript regex?

like image 627
php_nub_qq Avatar asked Sep 16 '25 20:09

php_nub_qq


1 Answers

To get the matched info use String#match:

var id = href.match(/\byoutube\.com\/[^?]*\?v=([^&]+)/i)[1];

And to make it even safer use:

var id = (href.match(/\byoutube\.com\/[^?]*\?v=([^&]+)/i) || [null, null])[1];

2nd approach is for the case when ?v= is missing in href variable.

like image 179
anubhava Avatar answered Sep 18 '25 10:09

anubhava