How can I get query string values in JavaScript?
20
Is there a plugin-less way of retrieving query string values via jQuery (or without)? 

If so, how, and if not what plugin do you recommend? 
improve this question | comment
Russell Hane Created at: 2013-11-13 17:07:35 UTC By Russell Hane
@Ralph - jQuery is a library and not a framework. - Dr. Jaycee McGlynn
I have wrote simple function for retrieving query string parameters without jQuery svlada.com/blog/2012/06/15/how-to-get-url-parameters-javascript - Camren Bednar
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables - Betty Koch
possible duplicate of JavaScript query string - Ruth Leffler
30 Answers
0
The problem with top answer on that question is that it's not support params placed after #, but sometimes it's needed to get this value also. I modify the unswer to let it parse full query string with hash sign also

var getQueryStringData = function(name){
        var result = null;
        var regexS = "[\\?&#]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec('?'+window.location.href.split('?')[1]);
        if(results != null){
            result = decodeURIComponent(results[1].replace(/\+/g, " "));
        }
        return result;
    };

0
I use regular expressions a lot but not for that.

It seems easier and more efficient to me to read the query string once in my application, and build an object from all the key/value pairs like:

var search = function() {
  var s = window.location.search.substr(1),
    p = s.split(/\&/), l = p.length, kv, r = {};
  if (l === 0) {return false;}
  while (l--) {
    kv = p[l].split(/\=/);
    r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
  }
  return r;
}();


For an URL like http://domain.com?param1=val1&param2=val2 you can get their value later in your code as search.param1 and search.param2.
0
Without jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));


With an URL like ?topic=123&name=query+string, the following will return:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)


Google method

Tearing Google's code I found the method they use: getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}


It is obfuscated, but it is understandable.

They start to look for parameters on the url from ? and also from the hash #. Then for each parameter they split in the equal sign b[f][p]("=") (which looks like indexOf, they use the position of the char to get the key/value). Having it split they check whether the parameter has a value or not, if it has they store the value o d, if not it just continue.

In the end the object d is returned, handling escaping and the + sign. This object is just like mine, it has the same behavior.

My method as a jQuery plugin

(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);


Usage

$.QueryString["param"]


Performance test (split method against regex method) (jsPerf)

Preparation code: methods declaration

Split test code

var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];


Regex test code

var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");


Testing in Firefox 4.0 x86 on Windows Server 2008 R2 / 7 x64

Split method: 144,780 ±2.17% fastest
Regex method: 13,891 ±0.85% | 90% slower
0
Improved version of Artem Barger's answer:

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


For more information on improvement see: http://james.padolsey.com/javascript/bujs-1-getparameterbyname/
0
Just another recommendation. 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")

0
Roshambo on snipplr.com has a really hot and simple script to achieve this described in Get URL Parameters with jQuery | Improved. With his script you also easily get to pull out just the parameters you want.

Here's the gist:

$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results)
    { 
        return 0; 
    }
    return results[1] || 0;
}


Then just get your parameters from the query string.

So if the URL/query string was xyz.com/index.html?lang=de.

Just call var langval = $.urlParam('lang');, and you've got it.

UZBEKJON has a great blog post on this as well, Get URL parameters & values with jQuery.
0
If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library.


  ...jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods.


If you want to just use plain JavaScript, you could use...

var getParamValue = (function() {
    var params;
    var resetParams = function() {
            var query = window.location.search;
            var regex = /[?&;](.+?)=([^&;]+)/g;
            var match;

            params = {};

            if (query) {
                while (match = regex.exec(query)) {
                    params[match[1]] = decodeURIComponent(match[2]);
                }
            }    
        };

    window.addEventListener
    && window.addEventListener('popstate', resetParams);

    resetParams();

    return function(param) {
        return params.hasOwnProperty(param) ? params[param] : null;
    }

})();​


Because of the new HTML History API and specifically history.pushState() and history.replaceState(), the URL can change which will invalidate the cache of parameters and their values.

This version will update its internal cache of parameters each time the history changes.
0
Keep it simple:

function qs(key) {
    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[key];
}


Call it from anywhere in the JavaScript code:

var result = qs('someKey');

0
Here's my stab at making Andy E's excellent solution into a full fledged jQuery plugin:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);


The syntax is:

var someVar = $.getQueryString('myParam');


Best of both worlds!
0
If you're doing more URL manipulation than simply parsing the querystring, you may find URI.js helpful. It is a library for manipulating URLs - and comes with all the bells and whistles. (Sorry for self-advertising here)

to convert your querystring into a map:

var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
  "foo": ["bar", "world"],
  "bar": "baz"
}


(URI.js also "fixes" bad querystrings like ?&foo&&bar=baz& to ?foo&bar=baz)
0
Why not just use 2 splits ?

function get(n){
      var half = location.search.split(n+'=')[1];
      return half? decodeURIComponent(half.split('&')[0]):null;
  }


I was reading all previous and more complete answer. But I think that is the simplest and faster method. You can check in this jsPerf benchmark 

To solve the problem in Rup's comment, add a conditional split by changing the first line to the two below.  But absolute accuracy means it's now slower than regexp (see jsPerf).

function get(n) {
    var half = location.search.split('&'+n+'=')[1];
    if (!half) half = location.search.split('?'+n+'=')[1];
    return half? decodeURIComponent(half.split('&')[0]):null;
}


So if you know you won't run into Rup's counter-case, this wins.  Otherwise, regexp.
0
I like Ryan Phelan's solution. But I don't see any point of extending jQuery for that? There is no usage of jQuery functionality.

On other hand I like the built-in function in Google Chrome: window.location.getParameter.

So why not to use this? Okay, other browsers don't have. So let's create this function if it does not exist:

if (!window.location.getParameter ) {
  window.location.getParameter = function(key) {
    function parseParams() {
        var params = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);

        while (e = r.exec(q))
            params[d(e[1])] = d(e[2]);

        return params;
    }

    if (!this.queryStringParams)
        this.queryStringParams = parseParams(); 

    return this.queryStringParams[key];
  };
}


This function is more or less from Ryan Phelan, but it is wrapped differently: clear name and no dependencies of other javascript libraries. More about this function on my blog.
0
Use the following to get a query param value given a key name:

function getParam(key) 
  {
  // Find the key and everything up to the ampersand delimiter
  var value=RegExp(""+key+"[^&]+").exec(window.location.search);
  // Return the unescaped value minus everything starting from the equals sign or an empty string
  return unescape(!!value ? value.toString().replace(/^[^=]+./,"") : "");
  }

0
Here is a fast way to get an object similar to the PHP $_GET array:

function get_query(){
    var url = location.href;
    var qs = url.substring(url.indexOf('?') + 1).split('&');
    for(var i = 0, result = {}; i < qs.length; i++){
        qs[i] = qs[i].split('=');
        result[qs[i][0]] = decodeURIComponent(qs[i][1]);
    }
    return result;
}


Usage:

var $_GET = get_query();


For the query string x=5&y&z=hello&x=6 this returns the object:

{
  x: "6",
  y: undefined,
  z: "hello"
}

0
These are all great answers, but I needed something a bit more robust, and thought you all might like to have what I created. It is a simple library method that does dissection and manipulation of url parameters. The static method has the following sub methods that can be called on the subject url:

getHost
getPath
getHash
setHash
getParams
getQuery
setParam
getParam
hasParam
removeParam
Example:

URLParser(url).getParam('myparam1')


var url = "http://www.test.com/folder/mypage.html?myparam1=1&myparam2=2#something";

function URLParser(u){
    var path="",query="",hash="",params;
    if(u.indexOf("#") > 0){
        hash = u.substr(u.indexOf("#") + 1);
        u = u.substr(0 , u.indexOf("#"));
    }
    if(u.indexOf("?") > 0){
        path = u.substr(0 , u.indexOf("?"));        
        query = u.substr(u.indexOf("?") + 1);
        params= query.split('&');
    }else
        path = u;
    return {
        getHost: function(){
            var hostexp = /\/\/([\w.-]*)/;
            var match = hostexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getPath: function(){
            var pathexp = /\/\/[\w.-]*(?:\/([^?]*))/;
            var match = pathexp.exec(path);
            if (match != null && match.length > 1)
                return match[1];
            return "";
        },
        getHash: function(){
            return hash;
        },
        getParams: function(){
            return params
        },
        getQuery: function(){
            return query;
        },
        setHash: function(value){
            if(query.length > 0)
                query = "?" + query;
            if(value.length > 0)
                query = query + "#" + value;
            return path + query;
        },
        setParam: function(name, value){
            if(!params){
                params= new Array();
            }
            params.push(name + '=' + value);
            for (var i = 0; i < params.length; i++) {
                if(query.length > 0)
                    query += "&";
                query += params[i];
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
        getParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', name);
        },
        hasParam: function(name){
            if(params){
                for (var i = 0; i < params.length; i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) == name)
                        return true;
                }
            }
            console.log('Query variable %s not found', name);
        },
        removeParam: function(name){
            query = "";
            if(params){
                var newparams = new Array();
                for (var i = 0;i < params.length;i++) {
                    var pair = params[i].split('=');
                    if (decodeURIComponent(pair[0]) != name)
                          newparams .push(params[i]);
                }
                params = newparams ;
                for (var i = 0; i < params.length; i++) {
                    if(query.length > 0)
                        query += "&";
                    query += params[i];
                }
            }
            if(query.length > 0)
                query = "?" + query;
            if(hash.length > 0)
                query = query + "#" + hash;
            return path + query;
        },
    }
}


document.write("Host: " + URLParser(url).getHost() + '<br>');
document.write("Path: " + URLParser(url).getPath() + '<br>');
document.write("Query: " + URLParser(url).getQuery() + '<br>');
document.write("Hash: " + URLParser(url).getHash() + '<br>');
document.write("Params Array: " + URLParser(url).getParams() + '<br>');
document.write("Param: " + URLParser(url).getParam('myparam1') + '<br>');
document.write("Has Param: " + URLParser(url).hasParam('myparam1') + '<br>');

document.write(url + '<br>');

// Remove first param
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove first param<br>');

// Add third param
url = URLParser(url).setParam('myparam3',3);
document.write(url + ' - Add third param<br>');

// Remove second param
url = URLParser(url).removeParam('myparam2');
document.write(url + ' - Add third param<br>');

// Add hash 
url = URLParser(url).setHash('newhash');
document.write(url + ' - Set Hash<br>');

// Remove last param
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove last param<br>');

// Remove a param that doesnt exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a param that doesnt exist<br>');

​

0
Some of the solutions posted here are inefficient. Repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. If you're not working with the HTML 5 History API, this is only necessary once per page load.  The other suggestions here also fail to decode the URL correctly.

var urlParams;
(window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

Example querystring: 


  ?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty


Result:

urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

alert(urlParams["mode"]);
// -> "front"

alert("empty" in urlParams);
// -> true


This could easily be improved upon to handle array-style query strings too.  An example of this is here, but since array-style parameters aren't defined in RFC 3986 I won't pollute this answer with the source code.  

Also, as pointed out in the comments, ; is a legal delimiter for key=value pairs.  It would require a more complicated regex to handle ; or &, which I think is unnecessary because it's rare that ; is used and I would say even more unlikely that both would be used.  If you need to support ; instead of &, just swap them in the regex.

 
If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you.  For example, in PHP you can write:

<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>

Much simpler!
0
function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3

0
Code golf:

var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
    var s = a[i].split("=");
    a[i]  = a[unescape(s[0])] = unescape(s[1]);
}


Display it!

for (i in a) {
    document.write(i + ":" + a[i] + "<br/>");   
};


On my Mac: test.htm?i=can&has=cheezburger displays

0:can
1:cheezburger
i:can
has:cheezburger

0
Roshambo jQuery method wasn't taking care of decode URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Just added that capability also while adding in  the return statement 

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;


Now you can find the updated gist:

$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;


}
0
Doesn't have enough reputation for comment, sigh.

Here's my edit to this excellent answer - with added ability to parse query strings with keys without values.

var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i) {
        var p=a[i].split('=', 2);
        if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
        b[p[0]] = p[1];
    }
    return b;
})((url.split('?'))[1].split('&'));


IMPORTANT! Parameter for that func in last line is different, it's just example how one can pass arbitrary url to it. You can use last line from Bruno answer to parse current url.

So what exactly changed? With url http://sb.com/reg/step1?param= results will be same. But with url http://sb.com/reg/step1?param Bruno solution returns object without keys, while mine returns object with key param and undefined value.
0
This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string.

I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on.

I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need.

Enjoy.

    function getQSP(sName, sURL) {
        var theItmToRtn = "";
        var theSrchStrg = location.search;
        if (sURL) theSrchStrg = sURL;

        var sOrig = theSrchStrg;

        theSrchStrg = theSrchStrg.toUpperCase();
        sName = sName.toUpperCase();
        theSrchStrg = theSrchStrg.replace("?", "&")
        theSrchStrg = theSrchStrg + "&";
        var theSrchToken = "&" + sName + "=";
        if (theSrchStrg.indexOf(theSrchToken) != -1) {
            var theSrchTokenLth = theSrchToken.length;
            var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
            var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
            theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
        }
        return unescape(theItmToRtn);
    }

0
From developer.mozilla.org:

function loadPageVar (sVar) {
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));

0
I like this one:

// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
    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;
}


Works great for me.
0
I developed a small library using techniques listed here to create an easy to use, drop-in solution to anyones troubles; It can be found here: 

https://github.com/Nijikokun/query-js

Usage

Fetching specific parameter/key:

query.get('param');


Using the builder to fetch the entire object:

var storage = query.build();
console.log(storage.param);


and tons more... check the github link for more examples.

Features

Caching on both decoding and parameters
Supports hash query strings #hello?page=3
Supports passing custom queries
Supports Array / Object Parameters user[]="jim"&user[]="bob"
Supports empty management &&
Supports declaration parameters without values name&hello="world"
Supports repeated parameters param=1&param=2
Clean, compact, and readable source 4kb
AMD, Require, Node support
0
http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash


Regular key/value pair (?param=value)
Keys w/o value (?param : no equal sign or value)
Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
Repeated Keys (?param=1&param=2)
Removes Empty Keys (?&& : no key or value)
Code:

var queryString = window.location.search || '';
var keyValPairs = [];
var params      = {};
queryString     = queryString.substr(1);

if (queryString.length)
{
   keyValPairs = queryString.split('&');
   for (pairNum in keyValPairs)
   {
      var key = keyValPairs[pairNum].split('=')[0];
      if (!key.length) continue;
      if (typeof params[key] === 'undefined')
         params[key] = [];
      params[key].push(keyValPairs[pairNum].split('=')[1]);
   }
}

How to Call:

params['key'];  // returns an array of values (1..n)

Output:

key            ["value"]
keyemptyvalue  [""]
keynovalue     [undefined, "nowhasvalue"]

0
I'm gonna throw my hat in the ring - I needed an object from the query string, and I hate lots of code. may not be the most robust in the universe but it's just a few lines of code.

var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
    q[i.split('=')[0]]=i.split('=')[1];
});


a URL like this.htm?hello=world&foo=bar will create:

{hello:'world', foo:'bar'}

0
Here is my version of query string parsing code on github

It's "prefixed" with jquery.*, but the parsing function itself don't use jQuery. Its pretty fast but still open for few simple performance optimizations.

Also it supports list & hash-tables encoding in URL, like: 

arr[]=10&arr[]=20&arr[]=100


or

hash[key1]=hello&hash[key2]=moto&a=How%20are%20you

0
function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​


And this is how you can use this function assuming the URL is


  http://dummy.com/?stringtext=jquery&stringword=jquerybyexample


var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');

0
One line code to get Query 

var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];

0
You don't need jQuery for that purpose. You can use pure JavaScript:

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

Your Answer