Reputation: 1318
I want to get the video id of a youtube video using regex.
I have the following regex:
var VideoID = inputstring.match(/watch\?v=[A-Z,a-z,0-9]+($|\&)/);
This works fine. If i for instance put in:
https://www.youtube.com/watch?v=prHVlkFM9oc&index=9&list=RDxEwgEw3k6UA
It return this:
watch?v=prHVlkFM9oc&
But I only want the [A-Z,a-z,0-9]+ part of the regex (prHVlkFM9oc in the above code).
How do I get this? I could cut away 9 chars from the start after the regex returns, but that shouldn't be necessary.
Upvotes: 0
Views: 52
Reputation: 19193
Simply use parenthesis ( )
to catch the part that you want to grab:
var match = inputstring.match(/watch\?v=([A-Za-z0-9]+)($|&)/);
// returns ["watch?v=prHVlkFM9oc&", "prHVlkFM9oc", "&"]
Now your result is in match[1]
;
Upvotes: 1
Reputation: 562
Well, if you are ok with VideoId variable you can do folowing: var parts = VideoId.split("="); so you can get that part as parts[1]
Upvotes: 1
Reputation: 786289
You can use a captured group here and grab the first index of the resulting array:
var VideoID = ( inputstring.match(/watch\?v=([^&]+)/) || ['', ''])[1];
//=> prHVlkFM9oc
Upvotes: 1