0

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.

3
  • 1
    Commas in a character class have no special meaning and are not used to separate ranges, so you can remove them. & is not a special character in a pattern, there is no need to escape it. Commented Feb 25, 2015 at 22:35
  • regular expressions are the wrong tool for parsing a query string. Commented Feb 25, 2015 at 22:41
  • 1
    What is the right tool then? Commented Feb 25, 2015 at 23:11

3 Answers 3

1

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];

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

Comments

1

You can use a captured group here and grab the first index of the resulting array:

var VideoID = ( inputstring.match(/watch\?v=([^&]+)/) || ['', ''])[1];
//=> prHVlkFM9oc

3 Comments

I presume case [' ', ' '] fires if the first regex returns no matches?
yes that is for safeguard measure if matches fail.
Good idea, deserves an upvote, however why not simply use [] instead of ['',''], the match would be undefined which makes total sense.
1

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]

Comments

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.