Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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

this will work.. You need call this function where you need get the parameter by passing its name..

function getParameterByName(name)
{

  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  alert(results[1]);
  if( results == null )
    return "";
  else
    return results[1];
}
share
1  
That's almost identical to the top regexp answer except you're matching the whole URL not just the query string part and you're not removing escapes in the result. – Rup Jan 22 '14 at 11:54

Get all querystring parameters including checkbox values (arrays).

Considering the a correct & normal use of GET parameters the things i see it's missing, on most functions, is the support for arrays and removing the hash data

So i wrote this function

function qs(a){
 if(!a)return {};
 a=a.split('#')[0].split('&');
 var b=a.length,c={},d,k,v;
 while(b--){
  d=a[b].split('=');
  k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
  c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
 }
 return c
}

Using shorthand operators & while-- loop the performance should be very good to.

Support:

  1. empty values (key= / key)
  2. key value (key=value)
  3. arrays (key[]=value)
  4. hash (the hash tag is split out)

Notes:

It does not support object arrays (key[key]=value)

If the space is + it remains a +.

add .replace(/\+/g, " ") if you need.

Usage:

qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')

Return:

{
    "empty": "",
    "key": "value",
    "array": [
        "1",
        "2"
    ]
}

Demo:

http://jsfiddle.net/ZQMrt/1/

Info

If you don't understand something or you can't read the function just ask i'm happy to explain what i did here.

If you think the function is unreadable and unmanainable i'm happy to rewrite the function for you , but consider that shorthand & bitwise operators are always faster than a standard syntax (mybe read about shorthands and bitwise operators in the ECMA-262 book or us your favorite searchengine).Rewriting the code in a standard readable syntax means performance loss.

share

Simple Solution with Plain JS and Regex

alert(getQueryString("p2"));

function getQueryString (Param) {
      return decodeURI("http://www.example.com/?p1=p11&p2=p2222".replace(new RegExp("^(?:.*[&?]" + encodeURI(Param).replace(/[.+*]/g, "$&") + "(?:=([^&]*))?)?.*$", "i"), "$1"));
    }

JsFiddle

share

This didn't work for me, I want to match `?b' as the 'b' parameter is present, and not match '?return' as the 'r' parameter, here is my solution.

window.query_param = function(name) {
  var param_value, params;

  params = location.search.replace(/^\?/, '');
  params = _.map(params.split('&'), function(s) {
    return s.split('=');
  });

  param_value = _.select(params, function(s) {
    return s.first === name;
  })[0];

  if (param_value) {
    return decodeURIComponent(param_value[1] || '');
  } else {
    return null;
  }
};
share

The shortest possible expression in terms of size to obtain a query object seems to be:

var params = {};
location.search.substr(1).replace(/([^&=]*)=([^&]*)&?/g,
  function () { params[decodeURIComponent(arguments[1])] = decodeURIComponent(arguments[2]); });

You can make use of the A element to parse a URI from a string into its location-like components (to get rid of #..., for example):

var a = document.createElement('a');
a.href = url;
// Parse a.search.substr(1)... as above
share

quick, easy, and fast:

The Function:

    function getUrlVar() {
        var result = {};
        var location = window.location.href.split('#');
        var parts = location[0].replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            result [key] = value;
        });
    return result ;
    }

Usage:

var varRequest = getUrlVar()["theUrlVarName"];
share

For those who wants a short method (with limitations):

location.search.split('myParameter=')[1]
share
3  
That's not enough for the general case: it assumes 1) that you're only interested in a single parameter 2) that it's guaranteed to be the last parameter in the line (i.e. you can guarantee that all browsers will put it last, or it's the only param on the page, and that you're not going to e.g. put the URL in an RSS feed aggregator where it might get utm parameters added) and 3) that there are no characters in the value that can be escaped for transmission, e.g. spaces or many symbols. – Rup Apr 14 '14 at 10:21
1  
There's no 1 size fits all methods. If you have a perfect solution in a one-short-liner, I'll be all eyes and ears to check that out. Above is a quick solution, not for general case, but for coders who want a light weight and quick solution to static implementations. In any case, thanks for your comment. – George Apr 14 '14 at 14:40
1  
(location.search.split('myParameter=')[1]).split('&')[0] ; this gives you the same result in case of multiple parameters. Still useful only for static implementations. – Anurag Aug 1 '14 at 7:05

Here is String prototype implementation:

String.prototype.getParam = function( str ){
    str = str.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp( "[\\?&]*"+str+"=([^&#]*)" );    
    var results = regex.exec( this );
    if( results == null ){
        return "";
    } else {
        return results[1];
    }
}

Example call:

var status = str.getParam("status")

str can be a query string or url

share

Here's an extended version of Andy E's linked "Handle array-style query strings"-version. Fixed a bug (?key=1&key[]=2&key[]=3; 1 is lost and replaced with [2,3]), made a few minor performance improvements (re-decoding of values, recalculating "[" position, etc.) and added a number of improvements (functionalized, support for ?key=1&key=2, support for ; delimiters). I left the variables annoyingly short, but added comments galore to make them readable (oh, and I reused v within the local functions, sorry if that is confusing ;).

It will handle the following querystring...

?test=Hello&person=neek&person[]=jeff&person[]=jim&person[extra]=john&test3&nocache=1398914891264

...making it into an object that looks like...

{
    "test": "Hello",
    "person": {
        "0": "neek",
        "1": "jeff",
        "2": "jim",
        "length": 3,
        "extra": "john"
    },
    "test3": "",
    "nocache": "1398914891264"
}

As you can see above, this version handles some measure of "malformed" arrays, i.e. - person=neek&person[]=jeff&person[]=jim or person=neek&person=jeff&person=jim as the key is identifiable and valid (at least in dotNet's NameValueCollection.Add):

If the specified key already exists in the target NameValueCollection instance, the specified value is added to the existing comma-separated list of values in the form "value1,value2,value3".

It seems the jury is somewhat out on repeated keys as there is no spec. In this case, multiple keys are stored as an (fake)array. But do note that I do not process values based on commas into arrays.

The code:

getQueryStringKey = function(key) {
    return getQueryStringAsObject()[key];
};


getQueryStringAsObject = function() {
    var b, cv, e, k, ma, sk, v, r = {},
        d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
        q = window.location.search.substring(1),
        s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter:   /([^&=]+)=?([^&]*)/g
    ;

    //# ma(make array) out of the v(alue)
    ma = function(v) {
        //# If the passed v(alue) hasn't been setup as an object
        if (typeof v != "object") {
            //# Grab the cv(current value) then setup the v(alue) as an object
            cv = v;
            v = {};
            v.length = 0;

            //# If there was a cv(current value), .push it into the new v(alue)'s array
            //#     NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
            if (cv) { Array.prototype.push.call(v, cv); }
        }
        return v;
    };

    //# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
    while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
        //# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry) 
        b = e[1].indexOf("[");
        v = d(e[2]);

        //# As long as this is NOT a hash[]-style key-value e(ntry)
        if (b < 0) { //# b == "-1"
            //# d(ecode) the simple k(ey)
            k = d(e[1]);

            //# If the k(ey) already exists
            if (r[k]) {
                //# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
                r[k] = ma(r[k]);
                Array.prototype.push.call(r[k], v);
            }
            //# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
            else {
                r[k] = v;
            }
        }
        //# Else we've got ourselves a hash[]-style key-value e(ntry) 
        else {
            //# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
            k = d(e[1].slice(0, b));
            sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));

            //# ma(make array) out of the k(ey) 
            r[k] = ma(r[k]);

            //# If we have a sk(sub-key), plug the v(alue) into it
            if (sk) { r[k][sk] = v; }
            //# Else .push the v(alue) into the k(ey)'s array
            else { Array.prototype.push.call(r[k], v); }
        }
    }

    //# Return the r(eturn value)
    return r;
};
share

Amazing how many overly complicated and incomplete solutions are posted here. Here's what I'm using:

/**
 * Returns a bare object of the URL's query parameters.
 * You can pass just a query string rather than a complete URL.
 * The default URL is the current page.
 */
function getUrlParams (url) {
    // http://stackoverflow.com/a/23946023/2407309
    if (typeof url == 'undefined') {
        url = window.location.search
    }
    var url = url.split('#')[0] // Discard fragment identifier.
    var queryString = url.split('?')[1]
    if (!queryString) {
        if (url.search('=') !== false) {
            queryString = url
        }
    }
    var urlParams = {}
    if (queryString) {
        var keyValuePairs = queryString.split('&')
        for (var i = 0; i < keyValuePairs.length; i++) {
            var keyValuePair = keyValuePairs[i].split('=')
            var paramName = keyValuePair[0]
            var paramValue = keyValuePair[1] || ''
            urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
        }
    }
    return urlParams
} // getUrlParams

Works with following URLs (values of getUrlParams()['test'] in parens):

example.com                         (undefined)
example.com?                        (undefined)
example.com?test                    (empty string)
example.com?test=                   (empty string)
example.com?test=0                  (the string '0')
example.com?test=0&test=override    (the string 'override')

Returning 'override' rather than '0' in the last case makes it consistent with PHP. Works in IE7.

share
1  
Why not? HTML 5 doesn't restrict the character set for input control names, nor is there any guarantee that they come from HTML anyway. I can't see why there would be a restriction to printable characters. – Rup Nov 18 '14 at 12:09
5  
'Amazing how many overly complicated and incomplete solutions are posted here' Lol, the irony.. – NiCk Newman Jul 13 at 16:14

Most pretty but basic:

data = {};
$.each(
    location.search.substr(1).split('&').filter(Boolean).map(function(kvpairs){
        return kvpairs.split('=')
    }),
    function(i,values) {
        data[values.shift()] = values.join('=')
    }
);

It doesn't handle values lists such as ?a[]=1&a[]2

share
// Parse query string
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g,
    m;
while (m = regex.exec(queryString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
share

This function will return a parsed JavaScript object with any arbitrarily nested values using recursion as necessary.

Here's a jsfiddle example.

[
  'a=a',
  '&b=a',
  '&b=b',
  '&c[]=a',
  '&c[]=b',
  '&d[a]=a',
  '&d[a]=x',
  '&e[a][]=a',
  '&e[a][]=b',
  '&f[a][b]=a',
  '&f[a][b]=x',
  '&g[a][b][]=a',
  '&g[a][b][]=b',
  '&h=%2B+%25'
].join('');

Given any of the above test examples.

ls = function() {
  var a, b, c, e;
  a = {};
  b = window.location.search.substring(1);
  c = function(d) {
    return d && decodeURIComponent(d.replace(/\+/g, ' '));
  };
  e = function(f, g, h) {
    var i, j, k, l;
    i = g.indexOf('[');
    if (i !== -1) {
      j = g.slice(0, i);
      k = g.slice(1 + i).slice(0, g.slice(1 + i).indexOf(']'));
      l = g.slice(1 + i).slice(1 + g.slice(1 + i).indexOf(']'));
      if (k) {
        if (typeof f[j] !== 'object') {
          f[j] = {};
        }
        f[j][k] = l ? e(f[j], k + l, h) : h;
      } else {
        if (typeof f[j] !== 'object') {
          f[j] = [];
        }
        f[j].push(h);
      }
      return f[j];
    } else {
      if (f.hasOwnProperty(g)) {
        if (typeof f[g] === 'object') {
          f[g].push(h);
        } else {
          f[g] = [].concat.apply([f[g]], [h]);
        }
      } else {
        f[g] = h;
      }
      return f[g];
    }
  };
  b.split('&').forEach(function(m) {
    e(a, c(m.split('=')[0]), c(m.split('=')[1]));
  });
  return a;
};
share
1  
Looks broadly good, but why pre-minify it? It's tricky to follow in places as-is; in particular you're doing a few nasty things around the right-square-bracket line. Also an input something like c[xx=a&c[]=b will crash it. – Rup Jul 1 '14 at 12:22

protected by Community Oct 23 '11 at 15:27

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, 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.