Reputation: 16055
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?
Upvotes: 4
Views: 383
Reputation: 785721
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.
Upvotes: 5