views:

2975

answers:

6

This should be very simple ( when you know the answer ). From this question

I want to give it a try to the posted solution. And my question is:

How to get the parameter value of a given url using javascript regexp?

I have:

 http://www.youtube.com/watch?v=Ahg6qcgoay4

I need:

 Ahg6qcgoay4

I tried:

http://www.youtube.com/watch\\?v=(w{11})

But: I suck...

A: 

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i
Swish
some youtube urls have a - as well, such as...http://www.youtube.com/watch?v=22hUHCr-Tos
MyWhirledView
@MyWhriledView Updated for the hyphen
Swish
+4  A: 

You almost had it, just need to escape special regex chars:

regex = /http\:\/\/www\.youtube\.com\/watch\?v=(\w{11})/;

url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Crescent Fresh
Should probably also put in a test for if the match fails, such as var m = url.match(regex); id = (m
Tadmas
I was struggling with that!!
OscarRyz
Don't know how to edit answers, but the above answer is incorrect, as it fails with video IDs containing the - dash character.Therefore the regex should be:/http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/
soupagain
A: 

Excelent, thanks /\?v=([a-z0-9-]+)\&?/i

jlrc23
+2  A: 

v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk

In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString

HttpUtility.ParseQueryString(url)["v"];

And you don't even need to check the key, as it will return null if the key is not in the collection.

Ion Todirel
+1  A: 

Why dont you take the string and split it

Example on the url

var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"

you can do a split as

var params = url.split("?")[1].split("&");

You will get array of strings with params as name value pairs with "=" as the delimiter.

moha297
that is a original idea, +1 for that, but I recommend using HttpUtility.ParseQueryString if you can live with referencing System.Web.dll, and not reinvent the wheel
Ion Todirel
A: 

/\?v=([a-z0-9-]+)\&?/i not match http://www.youtube.com/watch?v=La_J77JDOZk&feature=related

BRAVO