Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract parameter value from url using regular expressions

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

I want to give the posted solution a try. My question is:

How to get the parameter value of a given URL using JavaScript regular expressions?

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...

like image 443
OscarRyz Avatar asked Aug 14 '09 22:08

OscarRyz


People also ask

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

How do I separate URL parameters?

URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).

How is a value passed in as a parameter from a URL request?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

What is used to extract the query parameters from the URL?

QueryParam annotation in the method parameter arguments. The following example (from the sparklines sample application) demonstrates using @QueryParam to extract query parameters from the Query component of the request URL.


2 Answers

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' 

Edit: Fix for regex by soupagain.

like image 55
Crescent Fresh Avatar answered Sep 20 '22 23:09

Crescent Fresh


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.

like image 33
moha297 Avatar answered Sep 19 '22 23:09

moha297