Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how? If not, is there a plugin which can do so?

share

locked by animuson Jul 25 '14 at 19:35

This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here

69  
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables –  Lorenzo Polidori Oct 29 '12 at 14:50
6  
Although the top solution to the question deserves its popularity because of its excellent observation that jQuery is not needed, its method of creating new regular expressions and re-parsing the query string for every parameter desired is extremely inefficient. Far more efficient (and versatile) solutions have been in existence for a long time, for example within this article reprinted here: htmlgoodies.com/beyond/javascript/article.php/11877_3755006_3/… –  Joseph Myers May 14 '13 at 6:00
1  
possible duplicate of JavaScript query string –  Cupcake Jul 31 '13 at 23:09
4  
Joseph, the "excellent observation that jQuery is not needed"? Of course it's not needed. Everything jQuery does, it does using JavaScript. People don't use jQuery because it does stuff that JavaScript can't do. The point of jQuery is convenience. –  Vladimir Kornea May 30 '14 at 1:12

73 Answers 73

Here's my own take on this. This first function decodes a URL string into an object of name/value pairs:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

And as an added bonus, if you change some of the args, you can use this second function to put the array of args back into the URL string:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};
share
1  
@greg to create the element in the browser engine, which will parse a url for you and provide search and href methods for interacting with the url string. –  BMitch Apr 18 '13 at 2:15

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)

share
function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

share

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.

share
1  
Looks like window.location.getParameter() has been removed from Chrome. –  mhenry1384 Sep 23 '14 at 17:38
1  
Yes, it is gone now, but I like this function and its name. –  Anatoly Mironov Sep 24 '14 at 8:06

Try this:

String.prototype.getValueByKey = function(k){
    var p = new RegExp('\\b'+k+'\\b','gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};

Then call it like so:

if(location.search != "") location.search.getValueByKey("id");

You can use this for cookies also:

if(navigator.cookieEnabled) document.cookie.getValueByKey("username");

This only works for strings that have "key=value[&|;|$]"... will not work on objects/arrays.

If you don't want to use String.prototype... move it to a function and pass the string as an argument

share

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
share

This code will create a object which have two method
1. isKeyExist: Check if particular parameter exist;
2. getValue: get value of particular parameter.

 var QSParam = new function() {
        var qsParm = {};
        var query = window.location.search.substring(1);
        var params = query.split('&');
        for (var i = 0; i < params.length; i++) {
            var pos = params[i].indexOf('=');
            if (pos > 0) {
                var key = params[i].substring(0, pos);
                var val = params[i].substring(pos + 1);
                qsParm[key] = val;
            }
        }
        this.isKeyExist = function(query){
            if(qsParm[query]){
                return true;
            }
            else{
               return false;
            }
        };     
        this.getValue = function(query){
            if(qsParm[query])
            {
                return qsParm[query];
            }
            throw "URL does not contain query "+ query;
        }
  };
share

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.

share

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
share
5  
I love your answer, especially how compact the script is, but you should probably be using decodeURIComponent. See xkr.us/articles/javascript/encode-compare and stackoverflow.com/questions/619323/… –  pluckyglen Aug 10 '11 at 1:08

I took this answer and added support for optionally passing the URL in as a parameter; falls back to window.location.search. Obviously this is useful for getting the query string parameters from URLs that are not the current page:

(function($, undef) {
  $.QueryString = function(url) {
    var pairs, qs = null, index, map = {};
    if(url == undef){
      qs = window.location.search.substr(1);
    }else{
      index = url.indexOf('?');
      if(index == -1) return {};
      qs = url.substring(index+1);
    }
    pairs = qs.split('&');
    if (pairs == "") return {};
    for (var i = 0; i < pairs.length; ++i)
    {
      var p = pairs[i].split('=');
      if(p.length != 2) continue;
      map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return map;
  };
})(jQuery);
share

I would rather use split() instead of Regex for this operation:

function getUrlParams() {
    var result = {};
    var params = (window.location.search.split('?')[1] || '').split('&');
    for(var param in params) {
        if (params.hasOwnProperty(param)) {
            paramParts = params[param].split('=');
            result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
        }
    }
    return result;
}
share

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);
    }
share
21  
you need to work on those var names –  ajax333221 May 25 '12 at 22:20

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!

share

protected by Community Oct 23 '11 at 15:27

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.