4

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?

7
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…? Commented Sep 18, 2014 at 11:35
  • To the best of my knowledge the ? in ^.*?youtube is useless because the * means zero or more times, and the ? means it's optional, which is redundant. Commented Sep 18, 2014 at 11:37
  • @Nateowami ? after * or + means to not be greedy, to stop at the following-up pattern. So in my case URLs like youtube.com... ( missing schema and www ) would be valid. Commented Sep 18, 2014 at 11:43
  • OK, good point. But without the ? it would still match cases without scheme or www. Commented Sep 18, 2014 at 11:53
  • 1
    This question is using a youtube URL as an example but this questions is more generic i.e. Javascript regex return capture group value Commented Apr 30, 2021 at 6:24

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Nateowami If the string doesn't match you'll get null back instead of an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.