Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a GET parameter from the URL in Javascript? [duplicate]

Possible Duplicate:
Use the get parameter of the url in javascript

Suppose I have this url:

s = 'http://mydomain.com/?q=microsoft&p=next'

In this case, how do I extract "microsoft" from the string? I know that in python, it would be:

new_s = s[s.find('?q=')+len('?q='):s.find('&',s.find('?q='))]
like image 877
TIMEX Avatar asked Oct 26 '09 08:10

TIMEX


People also ask

How can I get multiple values from GET request URL?

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

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.

How do I find URL parameters?

For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object. By using Separating and accessing each parameter pair.

How do you add multiple parameters to a URL?

To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.


2 Answers

I use the parseUri library available here: http://stevenlevithan.com/demo/parseuri/js/

It allows you to do exactly what you are asking for:

var uri = 'http://mydomain.com/?q=microsoft&p=next';
var q = uri.queryKey['q'];
// q = 'microsoft'
like image 117
Chris Dutrow Avatar answered Dec 26 '22 17:12

Chris Dutrow


(function(){

    var url = 'http://mydomain.com/?q=microsoft&p=next'
    var s = url.search.substring(1).split('&');

    if(!s.length) return;

    window.GET = {};

    for(var i  = 0; i < s.length; i++) {

        var parts = s[i].split('=');

        GET[unescape(parts[0])] = unescape(parts[1]);

    }

}())

Think this will work..

like image 43
opHASnoNAME Avatar answered Dec 26 '22 18:12

opHASnoNAME