32

How to extract the query string from the URL in javascript?

Thank you!

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
Jayesh
  • 3,891
  • 11
  • 55
  • 83
  • 3
    possible duplicate of [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Sindre Sorhus Nov 15 '13 at 18:16

10 Answers10

48

You can easily build a dictionary style collection...

function getQueryStrings() { 
  var assoc  = {};
  var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
  var queryString = location.search.substring(1); 
  var keyValues = queryString.split('&'); 

  for(var i in keyValues) { 
    var key = keyValues[i].split('=');
    if (key.length > 1) {
      assoc[decode(key[0])] = decode(key[1]);
    }
  } 

  return assoc; 
} 

And use it like this...

var qs = getQueryStrings();
var myParam = qs["myParam"]; 
codeling
  • 11,056
  • 4
  • 42
  • 71
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • 1
    I hope you don't mind, I edited your answer. `unescape` is deprecated and should be replaced with `decodeURIComponent`, you shouldn't decode the full search string because it will decode encoded ampersands or equals in the parameters e.g. `?test=fish%26chips`. Also, I improved it to correctly decode `+` into a space. See my answer to a similar question [here](http://stackoverflow.com/questions/901115/get-querystring-with-jquery/2880929#2880929) – Andy E Jul 01 '10 at 10:54
  • 3
    @Andy No, I don't mind at all! I agree with you. It would have handled basic query strings just fine, but now this is a more *complete* answer. – Josh Stodola Jul 01 '10 at 13:11
  • 1
    It says: `Uncaught SyntaxError: Invalid regular expression: /+/: Nothing to repeat`, should I care? – The Student Sep 20 '10 at 17:38
  • @Tom Yes that is an error that needs to be fixed (It is @Andy E's fault :P) I've updated the answer to be correct. – Josh Stodola Sep 20 '10 at 19:01
  • 1
    I was noticing that the function was failing if no parameters were specified, so I edited the function (pending peer review)! With my small addition, it would return an empty array if there are no parameters, which I think is the expected result (instead of an uncaught exception). – codeling Dec 03 '11 at 00:59
  • Splitting on '=' is incorrect behavior. -- Only the first equal sign encountered is part of the parameter name; any further equal signs (before the ampersand), should be treated as part of the value. – BrainSlugs83 Mar 15 '17 at 18:34
37

If you're referring to the URL in the address bar, then

window.location.search

will give you just the query string part. Note that this includes the question mark at the beginning.

If you're referring to any random URL stored in (e.g.) a string, you can get at the query string by taking a substring beginning at the index of the first question mark by doing something like:

url.substring(url.indexOf("?"))

That assumes that any question marks in the fragment part of the URL have been properly encoded. If there's a target at the end (i.e., a # followed by the id of a DOM element) it'll include that too.

Syntactic
  • 10,721
  • 3
  • 25
  • 25
3

You need to simple use following function.

function GetQueryStringByParameter(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

--- How to Use ---

var QueryString= GetQueryStringByParameter('QueryString');
user2788596
  • 344
  • 2
  • 12
3

Here's the method I use...

function Querystring() {
    var q = window.location.search.substr(1), qs = {};
    if (q.length) {
        var keys = q.split("&"), k, kv, key, val, v;
        for (k = keys.length; k--; ) {
            kv = keys[k].split("=");
            key = kv[0];
            val = decodeURIComponent(kv[1]);
            if (qs[key] === undefined) {
                qs[key] = val;
            } else {
                v = qs[key];
                if (v.constructor != Array) {
                    qs[key] = [];
                    qs[key].push(v);
                }
                qs[key].push(val);
            }
        }
    }
    return qs;
}

It returns an object of strings and arrays and seems to work quite well. (Strings for single keys, arrays for the same key with multiple values.)

kleopatra
  • 51,061
  • 28
  • 99
  • 211
B.B
  • 31
  • 1
1

Very Straightforward!

function parseQueryString(){
    var assoc = {};
    var keyValues = location.search.slice(1).split('&');
    var decode = function(s){
        return decodeURIComponent(s.replace(/\+/g, ' '));
    };

    for (var i = 0; i < keyValues.length; ++i) {
        var key = keyValues[i].split('=');
        if (1 < key.length) {
            assoc[decode(key[0])] = decode(key[1]);
        }
    }

    return assoc;
}
Andrew
  • 3,733
  • 1
  • 35
  • 36
1

Works for me-

function querySt(Key) {

    var url = window.location.href;

    KeysValues = url.split(/[\?&]+/); 

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

            KeyValue= KeysValues[i].split("=");

            if (KeyValue[0] == Key) {

                return KeyValue[1];

        }

    }

}

function GetQString(Key) {     

    if (querySt(Key)) {

         var value = querySt(Key);

         return value;        

    }

 }
nils
  • 25,734
  • 5
  • 70
  • 79
Abhimanyu Garg
  • 416
  • 4
  • 10
1

There is a new API called URLSearchParams in browsers which allow you to extract and change the values of the query string.

Currently, it seems to be supported in Firefox 44+, Chrome 49+ and Opera 36+.

Initialize/Input

To get started, create a new URLSearchParams object. For current implementations, you need to remove the "?" at the beginning of the query string, using slice(1) on the querystring, as Jake Archibald suggests:

var params = new URLSearchParams(window.location.search.slice(1)); // myParam=12

In later implementations, you should be able to use it without slice:

var params = new URLSearchParams(window.location.search); // myParam=12

Get

You can get params from it via the .get method:

params.get('myParam'); // 12

Set

Params can be changed using .set:

params.set('myParam', 'newValue');

Output

And if the current querystring is needed again, the .toString method provides it:

params.toString(); // myParam=newValue

There are a host of other methods in this API.

Polyfill

As browser support is still pretty thin, there is a small polyfill by Andrea Giammarchi (<3kB).

nils
  • 25,734
  • 5
  • 70
  • 79
  • This is great. I'd like to add one other positive about this method is that it appears to decode the values automatically. For example, if a value contains an encoded @ sign (%40), this method will return "@" instead of the encoded value of "%40". – Americus Mar 18 '16 at 17:51
0

You can use this Javascript :

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

OR

You can also use the plugin jQuery-URL-Parser allows to retrieve all parts of URL, including anchor, host, etc.

Usage is very simple and cool:

$.url().param("itemID")

via James&Alfa

Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
0

I have use this method

function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
Amay Kulkarni
  • 828
  • 13
  • 16
0
// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);

console.log(urlParams.has('post')); // true

console.log(urlParams.get('action')); // "edit"

console.log(urlParams.getAll('action')); // ["edit"]

console.log(urlParams.toString()); // "?post=1234&action=edit"

console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"
Enea Dume
  • 3,014
  • 3
  • 21
  • 36
praveen kedar
  • 188
  • 2
  • 5