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

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

    
I use the plugin getUrlParam described in jQuery-Plugin – getUrlParam (version 2). – coma May 23 '09 at 8:19
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 – user456814 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

up vote 5342 down vote accepted

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

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

Usage:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)


Note: If a parameter is present several times (?foo=lorem&foo=ipsum), you will get the first value (lorem). There is no standard about this and usages vary, see for example this question: Authoritative position of duplicate HTTP GET query keys.

share
871  
No one's saying it can't be done with pure Javascript. If you're already using jQuery, and jQuery has a function to do this, then it would make sense to use jQuery instead of reinventing the wheel with a new function. – Cerin Jan 31 '11 at 22:05
102  
How does this function handle http://www.mysite.com/index.php?x=x1&x=x2&x=x3 The value of field x is ambiguous. – dpp Jul 9 '11 at 6:34
63  
this also doesn't handle multi-valued keys, which are also perfectly legal. – hurrymaplelad Oct 7 '11 at 8:47
14  
For a querystring of ?mykey=0&m.+key=1, calling getParameterByName("m.+key") would return 0 instead of 1. You need to escape the regular expression metacharacters in name before building your regular expression. And you only need to call .replace() once by using the global flag and using "\\$&" as the replacement expression. You should search on location.search instead of location.href. An answer with over 400 upvotes should account for these details. – gilly3 Dec 9 '11 at 22:28
16  
This is the worst answer to any question that I've ever seen. Not calling a standard, debugged and maintained library for something so basic is madness... – frabcus Feb 5 '13 at 23:12

URLSearchParams

Firefox 44+, Opera 36+ and Chrome 49+ support the URLSearchParams API:

Safari Nightly has implemented it as well.

It is not standardized by W3C, but it is a living standard by WhatWG.

You can use it on location, but you need to remove the ? question mark (for example, with .slice(1)):

let params = new URLSearchParams(location.search.slice(1));

Or of course on any URL:

let url = new URL('https://example.com?foo=1&bar=2');
let params = new URLSearchParams(url.search.slice(1));

And you read/set parameters through the get(KEY), set(KEY, VALUE), append(KEY, VALUE) api. You can also iterate over all values for (let p of params) {}.

There's also a google-suggested URLSearchParams polyfill, a reference implementation, and a sample page if you want to start using this API without relying on latest version of Chrome/Firefox/Opera.

share
    
@DanDascalescu Fixed. – Paul Sweatte Jun 9 '15 at 16:21
2  
YES! finally. four years later, we have a living standard and a polyfill! Now we just need 100x more upvotes to get this to the top so people will find and use it. – DanO Sep 23 at 16:50

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. It's pretty fast, but still open for few simple performance optimizations.

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

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

or

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

jQuery.toQueryParams = function(str, separator) {
    separator = separator || '&'
    var obj = {}
    if (str.length == 0)
        return obj
    var c = str.substr(0,1)
    var s = c=='?' || c=='#'  ? str.substr(1) : str; 

    var a = s.split(separator)
    for (var i=0; i<a.length; i++) {
        var p = a[i].indexOf('=')
        if (p < 0) {
            obj[a[i]] = ''
            continue
        }
        var k = decodeURIComponent(a[i].substr(0,p)),
            v = decodeURIComponent(a[i].substr(p+1))

        var bps = k.indexOf('[')
        if (bps < 0) {
            obj[k] = v
            continue;
        } 

        var bpe = k.substr(bps+1).indexOf(']')
        if (bpe < 0) {
            obj[k] = v
            continue;
        }

        var bpv = k.substr(bps+1, bps+bpe-1)
        var k = k.substr(0,bps)
        if (bpv.length <= 0) {
            if (typeof(obj[k]) != 'object') obj[k] = []
            obj[k].push(v)
        } else {
            if (typeof(obj[k]) != 'object') obj[k] = {}
            obj[k][bpv] = v
        }
    }
    return obj;

}
share
    
this is what I have been looking for. the support for [] kind of mappings. – Jimmy Ilenloa Jan 25 '15 at 16:42

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

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

I used this code (JavaScript) to get the what is passed through the URL:

function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
                vars[key] = value;
            });
            return vars;
        }

Then to assign the value to a variable, you only have to specify which parameter you want to get, ie if the URL is example.com/?I=1&p=2&f=3

You can do this to get the values:

var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];

then the values would be:

getI = 1, getP = 2 and getF = 3
share
    
That's neat, although it's missing decodeURIComponent on the key and the value and you probably don't need the i flag on the regexp (not that that really matters). – Rup Sep 8 '13 at 22:40

The following code will create an object which has two methods:

  1. isKeyExist: Check if a particular parameter exist
  2. getValue: Get the value of a 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

This is very simple method to get parameter value(query string)

Use gV(para_name) function to retrieve its value

var a=window.location.search;
a=a.replace(a.charAt(0),""); //Removes '?'
a=a.split("&");

function gV(x){
 for(i=0;i<a.length;i++){
  var b=a[i].substr(0,a[i].indexOf("="));
  if(x==b){
   return a[i].substr(a[i].indexOf("=")+1,a[i].length)}
share

If you do not wish to use a JavaScript library you can use the JavaScript string functions to parse window.location. Keep this code in an external .js file and you can use it over and over again in different projects.

// Example - window.location = "index.htm?name=bob";

var value = getParameterValue("name");

alert("name = " + value);

function getParameterValue(param)
{
    var url = window.location;
    var parts = url.split('?');
    var params = parts[1].split('&');
    var val = "";

    for ( var i=0; i<params.length; i++)
    {
        var paramNameVal = params[i].split('=');

        if ( paramNameVal[0] == param )
        {
            val = paramNameVal[1];
        }
    }
    return val;
}
share

I recommend Dar Lessons as a good plugin. I have worked with it fo a long time. You can also use the following code. Jus put var queryObj = {}; before document.ready and put the bellow code in the beginning of document.ready. After this code you can use queryObj["queryObjectName"] for any query object you have

var querystring = location.search.replace('?', '').split('&');
for (var i = 0; i < querystring.length; i++) {
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    queryObj[name] = value;
}
share
    
Two plugs for Dar Lessons in two posts? I don't think we can recommend the current version at least: it's vulnerable to script injection attacks. (I've emailed him to let him know). Like a lot of the split('=') solutions here already you're missing decodeURIComponent, and you might also want to handle missing values more gracefully too. – Rup Jul 15 '13 at 10:37
    
Dar Lessons has now released 1.1 which fixes the script injection attack. – Rup Jul 17 '13 at 8:31

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
    
That's basically the same as the top answer though, less some some of the unescaping, just put on the String.prototype. – Rup Apr 19 '14 at 12:33
    
@Rup This is useful for parsing any string query, not just in a URL. for example Oauth2 returns token response as a query string, this String prototype will be useful for parsing, most important is [\\?&]* instead of [\\?&] in RegExp, for parsing query string staring with new line – krisrak Apr 19 '14 at 15:44

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
    
Which answer here didn't work for you, with those problems? (That'd be worth a comment on the answer itself, and I'd be interested to know too.) As for your solution, that looks like it's just a string-split solution using underscore.js? You're missing a call to decodeURIComponent probably. – Rup Feb 13 '14 at 16:07
    
Nice catch, I added the decodeURIComponent (and a spec for it). The most upvoted answer (the 2600 points one for jolly) doesn't works as expected: doesn't returns null for non-found parameters, and doesn't detect ?b for instance a present parameter. – Dorian Feb 13 '14 at 17:12

tl;dr

A quick, complete solution, which handles multivalued keys and encoded characters.

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})

//using ES6
location.search.substr(1).split("&").forEach((item) => {var [k,v] = item.split("="); v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
Multi-lined:
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]);
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) //short-circuit
})
Example:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> qd.a[1]    // "5"
> qd["a"][1] // "5"

short-circuit evaluation, ES6 Destructuring assignments, Arrow functions


Read more... about the Vanilla JavaScript solution.

To access different parts of a URL use location.(search|hash)

Easiest (dummy) solution

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
  • Handles empty keys correctly.
  • Overrides multi-keys with last value found.
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

Multi-valued keys

Simple key check (item in dict) ? dict.item.push(val) : dict.item = [val]

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})
  • Now returns arrays instead.
  • Access values by qd.key[index] or qd[key][index]
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

Encoded characters?

Use decodeURIComponent() for the second or both splits.

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
Example:
"?a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]

*!!! Please note, that decodeURIComponent(undefined) returns string "undefined". The solution lies in a simple usage of &&, which ensures that decodeURIComponent() is not called on undefined values. (See the "complete solution" at the top.)

v = v && decodeURIComponent(v);
share
    
Nice. The only thing I would change - is if there aren't more than one values for a key there is no need for it to be an array. Only use array if there is more than one value per key. – Pavel Nikolov Jan 16 '14 at 21:03
1  
@PavelNikolov I think it would introduce difficulties getting sometimes an array and sometimes a value. You would have to check for it first, now you only check the length, because you will be using cycles for retrieving those values anyways. Also this was meant to be the easiest, but functional, solution here. – Qwerty Jan 16 '14 at 21:20
    
@twig will not work in IE8 – sqram Mar 20 '14 at 18:12
1  
Flattened out a bit for readability, made into a function, and re-used split call: function parseQueryString() { var qd = {}; location.search.substr(1).split("&").forEach(function(item) { var parts = item.split("="); var k = parts[0]; var v = decodeURIComponent(parts[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v,] }); return qd; } – Casey Feb 6 '15 at 10:04
1  
decodeDocumentURI(undefined) returns "undefined" instead of undefined. A functional but not very elegant patch: var qd = {}; location.search.substr(1).split("&").forEach( function(item) { var s = item.split("="), k = s[0], v; if(s.length>1) v = decodeURIComponent(s[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v] }) – loop Jun 24 '15 at 12:07

Here's what I'm using:

/**
 * Examples:
 * getUrlParams()['myparam']    // url defaults to the current page
 * getUrlParams(url)['myparam'] // url can be just a query string
 *
 * Results of calling `getUrlParams(url)['myparam']` with various urls:
 * example.com                               (undefined)
 * example.com?                              (undefined)
 * example.com?myparam                       (empty string)
 * example.com?myparam=                      (empty string)
 * example.com?myparam=0                     (the string '0')
 * example.com?myparam=0&myparam=override    (the string 'override')
 *
 * Origin: http://stackoverflow.com/a/23946023/2407309
 */
function getUrlParams (url) {
    var urlParams = {} // return value
    var queryString = getQueryString()
    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 // functions below
    function getQueryString () {
        var reducedUrl = url || window.location.search
        reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
        var queryString = reducedUrl.split('?')[1]
        if (!queryString) {
            if (reducedUrl.search('=') !== false) { // URL is a query string.
                queryString = reducedUrl
            }
        }
        return queryString
    } // getQueryString
} // getUrlParams

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

share
    
That's because everyone seems to have different requirements for handling keys without values or handling duplicated keys by building arrays of values, etc. There are plenty of split answers already but I don't see one that does exactly the same as this one, true. (FWIW I think paramName needs to be decodeURIComponented too technically, though I doubt anyone would use non-trivial params.) – Rup Jun 2 '14 at 7:22
    
Parameter names should never need decoding. – Vladimir Kornea Nov 18 '14 at 11:43
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
    
It's never good practice. – Vladimir Kornea Nov 18 '14 at 13:56
7  
'Amazing how many overly complicated and incomplete solutions are posted here' Lol, the irony.. – NiCk Newman Jul 13 '15 at 16:14

Keep it simple in plain JavaScript code:

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');
share
1  
I think you are doing something similar as me, but I think my approach is MUCH simplier stackoverflow.com/a/21152762/985454 – Qwerty Jan 16 '14 at 14:52

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! The parameter for that function in the last line is different. It's just an example of how one can pass an arbitrary URL to it. You can use last line from Bruno's answer to parse the 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's solution returns an object without keys, while mine returns an object with key param and undefined value.

share

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 a URL like http://domain.com?param1=val1&param2=val2 you can get their value later in your code as search.param1 and search.param2.

share

If you have Underscore.js or lodash, a quick and dirty way to get this done is:

_.object(window.location.search.slice(1).split('&').map(function (val) { return val.split('='); }));
share
    
Neat. Compared to the top split-based answer though you're missing handling of +s and the decodeURIComponent calls, but for simple values this will be enough. – Rup Nov 20 '13 at 15:32
    
Yeah, it's really just meant for grabbing simple alphanumeric tokens. In a current project, it's all I needed, so I didn't really want a hulking function. – acjay Nov 21 '13 at 6:18
1  
this is what I use to make a key value object of the query parameters: _.chain(document.location.search.slice(1).split('&')).invoke‌​('split', '=').object().value() – David Fregoli Jan 7 '14 at 14:46

Use:

  $(document).ready(function () {
      var urlParams = {};
      (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);

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

Please check and let me know your comments. Also refer to How to get querystring value using jQuery.

share
    
That's identical to Soheil's answer which is itself a copy of Andy E's answer wrapped in jQuery and with the check on the end. You've also copied Soheil's mistake in the last section: there's no way that urlParams["q1"] can === 1 since it will always be a string not an integer at that point, and also return 1 from $(document).ready() doesn't really make sense either. Where did you get this code from? – Rup Jul 23 '13 at 13:10
2  
@Rup : I have got this from codeproject.com/Tips/529496/Handling-QueryString-Using-jQuer‌​y – Pushkraj Jul 23 '13 at 13:14

See this post or use this:

<script type="text/javascript" language="javascript">
    $(document).ready(function()
    {
        var urlParams = {};
        (function ()
        {
            var match,
            pl= /\+/g,  // Regular expression for replacing addition symbol with a space
            search = /([^&=]+)=?([^&]*)/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            query  = window.location.search.substring(1);

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

        if (urlParams["q1"] === 1)
        {
            return 1;
        }
    });
</script>
share
    
Your sample usage - returning from a document ready - seems odd, and AFAICS it'll never work: decode() will only ever return a string and your triple-equals-comparing it to an integer. Otherwise seems a neat solution. – Rup Jul 10 '13 at 11:35
    
... although it's the same as Andy E's solution above. – Rup Jul 10 '13 at 11:42
    
The link is broken. – Peter Mortensen Jul 24 at 14:08

I did a small URL library for my needs here: https://github.com/Mikhus/jsurl

It's a more common way of manipulating the URLs in JavaScript. Meanwhile it's really lightweight (minified and gzipped < 1 KB) and has a very simple and clean API. And it does not need any other library to work.

Regarding the initial question, it's very simple to do:

var u = new Url; // Current document URL
// or
var u = new Url('http://user:[email protected]:8080/some/path?foo=bar&bar=baz#anchor');

// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);

// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']

alert(u.query.foo);
alert(u.query.woo);
alert(u);
share
    
That's interesting. Why decode the value manually? You'll also limited in the top character code you can accept as UTF-8, although I realise you're unlikely to ever hit that in practice. – Rup Apr 19 '13 at 9:00
    
Why decoding in that way explained here: unixpapa.com/js/querystring.html Actually, I've took the code for that idea from there, what is stated in a top-level comment at my script – Mikhus Apr 19 '13 at 9:28

The problem with the top answer on that question is that it's not-supported parameters placed after #, but sometimes it's needed to get this value also.

I modified the answer to let it parse a full query string with a 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;
};
share
1  
That's interesting if you need it but there's no standard for the format of the hash part AFAIK so it's not fair to call that out as a weakness of the other answer. – Rup Apr 22 '13 at 12:48
2  
Yes, I know. But in my app i integrate 3rd party js navigation, which have some parameters after hash sign. – Ph0en1x Apr 22 '13 at 14:15
    
For example, in the Google search page, the searching query is followed by the hash sign '#'. – etlds Jun 26 '14 at 14:51

If you want array-style parameters URL.js supports arbitrarily nested array-style parameters as well as string indexes (maps). It also handles URL decoding.

url.get("val[0]=zero&val[1]=one&val[2]&val[3]=&val[4]=four&val[5][0]=n1&val[5][1]=n2&val[5][2]=n3&key=val", {array:true});
// Result
{
    val: [
        'zero',
        'one',
        true,
        '',
        'four',
        [ 'n1', 'n2', 'n3' ]
    ]
    key: 'val'
}
share

A very lightweight jQuery method:

var qs = window.location.search.replace('?','').split('&'),
    request = {};
$.each(qs, function(i,v) {
    var pair = v.split('=');
    return request[pair[0]] = pair[1];
});
console.log(request);

And to alert, for example ?q

alert(request.q)
share
1  
Neat. There's a few answers in the same vein already - iterating over a split - albeit none using jQuery's each, and I don't think any of them are perfect yet either. I don't understand the return in your closure though, and I think you need to decodeUriComponent the two pair[] values as you read them. – Rup Apr 2 '13 at 8:48
    
yea having the decodeUriComponent is def best practice- i just kinda wrote that on the fly. As for the return... i just stay in the habit of returning something. totally not necessary – Roi May 13 '13 at 20:55

I needed an object from the query string, and I hate lots of code. It 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'}
share
4  
Neat. According to Mozilla, though, forEach doesn't work on IE7 or 8 and I suspect that'll fall over if there's no query string at all. One minimal improvement that would cover more cases would be to decodeURIComponent the value as you store it - and arguably the key as well, but you're less likely to use odd strings in that. – Rup Feb 15 '13 at 10:39
    
Good idea. Like I said. It's not super robust. But many of my clients now see so little traffic from IE7/8 that I'm no longer sweating it. – tim Jun 27 '13 at 19:21
1  
Nice and simple. Doesn't handle array parameters nor ?a&b&c but this is really very readable (and incidentally similar to my first idea). Also the split is redundant but I've got bigger performance fish to fry than splitting a 10 character string twice. – cod3monk3y Feb 25 '14 at 22:44
    
when querystring is "?hello=world&one=a=b&two=2" then when you grab the value of 'one' you only get the part before the first '=' in the value. its value shud be 'a=b' but you only get 'a' because you split 'one=a=b' on '='. this is simply buggy. :(( – Shawn Kovac May 19 '15 at 21:30

One-liner to get the query:

var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
share
5  
Triggers error if the key doesn't exist, try this maybe? (location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1] – Brad Koch Jan 28 '13 at 20:51
    
@Brad, of course it's undefined, since that's the key you're looking for. if your query is?hello=world, var value = location.search.match(new RegExp("hello" + "=(.*?)($|\&)", "i"))[1]; will return "world" – tim Feb 13 '13 at 1:38
1  
@BradKoch I found your solution this best, especially with a short circuit to an empty string (window.location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1] || ''; – rob Sep 30 '14 at 7:41

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 the first parameter
url = URLParser(url).removeParam('myparam1');
document.write(url + ' - Remove the first parameter<br>');

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

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

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

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

// Remove a parameter that doesn't exist
url = URLParser(url).removeParam('myparam3');
document.write(url + ' - Remove a parameter that doesn\"t exist<br>');
share

Just use two splits:

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

I was reading all the previous and more complete answers. 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 !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}

So if you know you won't run into Rup's counter-case, this wins. Otherwise, regexp.

share
5  
Very neat! It won't work though if you have an earlier value with a key name that ends with the one you want, e.g. get('value') on http://the-url?oldvalue=1&value=2. – Rup Sep 4 '12 at 11:46
1  
However, if you know the parameter name are expecting, This will be the faster approach. – Martin Borthiry May 16 '13 at 17:57
    
Edited: If you just test that half is truthy, this returns null for an empty parameter like ?param=. It should return the empty string in this case, and checking half !== undefined solves that. – philh Jun 17 '14 at 15:03
    
Cool! I made a one-liner: function get(param){return decodeURIComponent((location.search.split(param+'=')[1]||'')‌​.split('&')[0])} – niutech Sep 1 '14 at 22:54
    
I had to change the second line to return half !== undefined ? decodeURIComponent(half[1].split('&')[0]) : null; to get it to work – divillysausages Jan 13 '15 at 22:54

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
    
That's similar to the fourth answer, albeit with less escaping and you don't accept ?key only params like that does (though you don't see them anymore). I'm not sure you need the i on the regexp options, and you're working with the whole href not just the search part which seems odd but it ought not make a difference. – Rup Apr 14 '14 at 10:32
    
@Rup Hi, Thank you for your comment - I can't see the similarity... He use decodeURIComponent which will work great but if we try it with accent characters - in some cases it fails (FF mostly) My answer As you can see is simple and quick that will fit most of the programmers who need a quick solution for query string variable extraction. Adding the i (case insensitivity) is a bit more flexible but can be removed, I agree. – Shlomi Hassid Apr 14 '14 at 13:05

A simple solution with plain JavaScript and regular expressions:

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

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 (the association bonus does not count).

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.