3

I need a regexp help, because for me it will take a lot of time , for you some minutes:)

I have youtube a URL :

http://www.youtube.com/watch?v=9_Hd8hXhg7o&feature=youtube_gdata 

I can't add this in embed object , for embed I have to change in this URL :

http://www.youtube.com/v/9_Hd8hXhg7o&hl=en_US&fs=1&

It means, that I want to add the youtube cod in some variable, something like this

var url = after regexp "9_Hd8hXhg7o";

"http://www.youtube.com/v/" + url +"&hl=en_US&fs=1&";

thanks !

1 Answer 1

4

This should do it:

var url = "http://www.youtube.com/watch?v=9_Hd8hXhg7o&feature=youtube_gdata";

var id = url.match(/(\?|&)v=(.*?)(&|$)/)[2];

var new_url = "http://www.youtube.com/v/" + id+"&hl=en_US&fs=1&";

This should work on pretty much every format you throw at it. This snippet looks for ?v= or &v= and any characters after that until an & symbol or end of line, so the ID can be found from these also:

http://www.youtube.com/watch?v=9_Hd8hXhg7o
http://www.youtube.com/watch?feature=youtube_gdata&v=9_Hd8hXhg7o
http://www.youtube.com/watch?fs=1&v=9_Hd8hXhg7o&feature=youtube_gdata&
Sign up to request clarification or add additional context in comments.

1 Comment

Rather than checking for & and ? separately, you can probably get away with just using \Wv=(.+?)(&|$). In fact, you can make it even easier by using some character classes: [?&]v=(\w+)

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.