3

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?

php_nub_qq
  • 12,762
  • 17
  • 59
  • 123
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec? – Bergi Sep 18 '14 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. – Nateowami Sep 18 '14 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. – php_nub_qq Sep 18 '14 at 11:43
  • OK, good point. But without the `?` it would still match cases without scheme or `www`. – Nateowami Sep 18 '14 at 11:53
  • @Nateowami I wasn't sure, that's why I put it there. Still without a question mark I have this inner doubt, don't know why :D – php_nub_qq Sep 18 '14 at 11:55
  • 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` – anubhava Apr 30 '21 at 06:24
  • Does this answer your question? [How do I get the YouTube video ID from a URL?](https://stackoverflow.com/questions/3452546/how-do-i-get-the-youtube-video-id-from-a-url) – oguz ismail May 16 '21 at 04:39

1 Answers1

4

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.

anubhava
  • 664,788
  • 59
  • 469
  • 547