Tell me more ×
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, and if not what plugin do you recommend?

share|improve this question
42  
plugin-less sounds funny... always thought jQuery kinda was a plugin... but I guess it's a framework and it can have its own plugins. – Mark Oct 28 '10 at 7:20
62  
@Ralph - jQuery is a library and not a framework. – ken Jan 17 '11 at 18:53
1  
I have wrote simple function for retrieving query string parameters without jQuery svlada.com/blog/2012/06/15/how-to-get-url-parameters-javascript – svlada Jun 25 '12 at 5:37
2  
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables – Lorenzo Polidori Oct 29 '12 at 14:50
show 3 more comments

48 Answers

1 2

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|improve this answer
show 3 more comments

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|improve this answer
show 1 more comment
function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

share|improve this answer

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|improve this answer
show 1 more comment

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|improve this answer

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|improve this answer

Nice.

To get a specific named argument in the query you could also do it the following way: JavaScript: Get URL Query Argument

Remember to url decode the value using the "unescape" method in JavaScript.

share|improve this answer

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|improve this answer

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|improve this answer

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) (jsPref)

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
share|improve this answer
5  
@Andy: I've posted an improved version. What do you think of it? – BrunoLM Oct 16 '10 at 1:51
1  
@Bruno: nice work... if only I could give you another +1 :-) – Andy E Oct 16 '10 at 9:45
4  
Curious why you'd make this a jQuery plugin when it doesn't have any jQuery specific code? – zachleat Feb 23 '11 at 13:55
3  
@zachleat if you don't have a framework your functions will just get spread across your code. If you extend jQuery you will have a scope for your functions, it won't be floating around somewhere in your code. I think that is the only reason. – BrunoLM Feb 23 '11 at 13:57
2  
Here is the jQuery version tweaked to pass JSLint (at least the semi-moving target of JSLint.com on 2011-06-15). Mostly just moving things around to appease The Crockford. – patridge Jun 15 '11 at 17:48
show 15 more comments

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|improve this answer
2  
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

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.

share|improve this answer
3  
with jQuery seems to mean to namespace the function to the jQuery object. Also, why is the invalid value 0? Sure, I could use strict equality check, but shouldn't it be null ? – alex Jun 17 '12 at 1:34

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|improve this answer

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|improve this answer

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|improve this answer
4  
you need to work on those var names – ajax333221 May 25 '12 at 22:20

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;

}

share|improve this answer

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|improve this answer
show 1 more comment
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] // 13
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3
share|improve this answer
3  
This is an interesting approach, returning an array containing values from the specified parameters. It does have at least one issue - not correctly URL decoding the values, and it would need to URL encode the parameter names used in match too. It will function on simple query strings in its present form though. ps don't forget to use the var keyword when declaring variables in for statements. – Andy E Jul 11 '10 at 8:28
1 2

protected by Community Oct 23 '11 at 15:27

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

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