By Subliminal Hash

2009-05-23 08:10:48 8 Comments

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?


@Andy E 2010-05-21 09:29:16

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  =;

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

Example querystring:



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

// -> "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. For those interested in a "polluted" version, look at campbeln's answer below.

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!


A new capability would be to retrieve repeated params as following myparam=1&myparam=2. There is not a specification, however, most of the current approaches follow the generation of an array.

myparam = ["1", "2"]

So, this is the approach to manage it:

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

    while (match = search.exec(query)) {
        if (decode(match[1]) in urlParams) {
            if (!Array.isArray(urlParams[decode(match[1])])) {
                urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
        } else {
            urlParams[decode(match[1])] = decode(match[2]);

@Nick Franceschina 2010-07-14 00:12:01

if you're doing a heavily ajax'd app, then you may be using the hash(#) to "enable the back button"... in that case the querystring would change all the time (see how facebook does it)... though these solutions ignore things that come after the # anways...

@Andy E 2010-07-14 09:20:48

@Nick: Anything after the hash resides in the window.location.hash property, which is separate from the property. If the hash changes, it doesn't affect the querystring at all.

@Jonathan 2010-10-28 05:59:17

Here's a version that emits them as a table with key/value properties. This is useful in case a key is assigned twice (bad practice, I know, but I had to deal with a lousy back-end.)

@Andy E 2010-10-28 09:21:13

@jonathan: you might have been able to modify my "php-array-style" example so that, instead of looking for [ in the parameter name, it checks if the key already exists. If it does exist, create an array. This would have at least allowed you to still look up sets of values by their name, you would have just had to check if the result was a string or an array of strings.

@Jonathan 2010-10-29 00:34:16

@AndyE that's a really good idea. Here's some code that does it that way:

@alex 2010-11-15 11:26:03

Don't forget the ; is a legal delimiter for GET key=value pairs. It is rare, but it takes 5 seconds to implement.

@Dan Rosenstark 2011-07-26 17:55:59

To say that the other solutions are "largely inefficient" assumes that you need all the querystring parameters on the client-side. Your solution becomes less efficient with each parameter that you DON'T need on the client side. The best answer to this question works in many cases where the assumption is that you do not need parameters.

@Andy E 2011-07-27 08:41:36

@Yar: I don't think it's that black and white. I'd say it's rare to need any query string values at all in JS. The best answer to this question is one that is consistently as efficient no matter which developer is using it. The currently accepted answer's performance relies solely on how the developer uses it and it's not a good idea to assume that such a developer competent enough to optimize their own code to compensate for the function's inefficiencies. To be fair, the question has received quite a few more answers since I wrote this, so I guess I could change the line.

@Dan Rosenstark 2011-07-27 19:39:27

@Andy E, I don't see how you could have an answer that's efficient regardless of how you use it. In one, you parse all query params up front. In another, you parse none up front and take a hit for each one. I was just trying to point out that the latter case is quite often desire-able... but not always ;)

@Andy E 2011-07-27 20:00:32

@Yar: of course, you have a point and I do agree to some extent :-) My argument was that the answers that are "largely inefficient" are so not because of the method they choose (parsing one at a time vs all at once), but because they lack certain optimizations (e.g. caching the result, precompiling the regex). In the future perhaps I'll create some sort of cross-breed version, just for you ;-)

@Dan Rosenstark 2011-07-27 20:44:27

Also, I might mention that the weak aspect of my argument is that if you have ANY control of the server-side at all, you could just parse all the querystring params there, and hand them over to javascript as an associative array. Your point is still valid, of course...

@Andy E 2011-07-27 21:53:28

@Yar: indeed, in PHP it should be as easy as echo 'var params = '.json_encode($_GET).';' - example. So simple!

@Damon 2011-08-29 19:54:28

I keep getting urlParams is not defined error, even with the code exactly as written.. tried to write it out as a separate function as well, still the same difficulty.

@Andy E 2011-08-30 00:15:49

@Damon: have you made sure you have the first line, var urlParams = {}; ? If that line is there, there's no way you could get that error..

@Helder S Ribeiro 2012-11-24 21:56:18

If you have repeated keys in the query string (like Google does if you do a new search from a search results page), shouldn't this have the last occurrence overwrite the others? I tried it and it's keeping the first value it's encountering.

@Andy E 2012-11-26 14:32:23

@obvio171 yes, the last occurrence of a key/value will always prevail. If you're seeing something different then it must be a result of slightly modifying the code in this answer or perhaps another issue with your own code.

@ManreeRist 2013-04-26 01:00:47

This is good but in my example, url: 'attr[]=309&attr[]=1772' .. only one attr: value is returned.

@Andy E 2013-04-26 07:33:35

@AndeeCrist: as my answer states, array-style parameters aren't defined by the RFC. However, I have a very basic example of them working in a link from my answer. It may need updating or tweaking, however.

@Matthew Gilliard 2013-05-14 14:32:58

To be fair, no specific format for the query string is defined by RFC3986. ?a=b&c=d is conventional, and a W3C recommendation for web forms, but the URI spec just defines query = *( pchar / "/" / "?" ).

@craigts 2013-09-04 19:26:58

For those of us using a fairly strict setup of JSHint swap the while(match = search.exec(query)) with while((match = search.exec(query)) !== null)

@Matt Dell 2013-11-07 12:10:09

I needed to get the values of multiple instances of query strings. For example, I might have car color chosen twice. The code as written above does not allow for the same parameter to be used twice. Because of that I've made this slight modification (requires changing urlParams to an array, e.g. - urlParams = []): urlParams.push({param: decode(match[1]), value: decode(match[2])});

@Gomino 2014-12-24 17:07:10

The regex is not working correctly, the first parameter is matching the all begining of the url: here is the fixed version: /([^?&=]+)=([^&]*)/g ->

@xr280xr 2016-02-04 14:39:58

I'm confused by your while loop. It looks like it will execute the regex on the same string over and over. How does it terminate?

@Andy E 2016-02-04 16:18:01

@xr280xr subsequent calls to exec() on a global regex will search from the index of the last match, and return null if there is no match. This means the while loop exits when there are no more matches in the target string.

@magician11 2018-07-01 15:18:04

@James Dullat 2020-01-23 16:07:09

Working like a Charm..... I have tried other method but none of them worked great. URLSearchParams doesn't supported by IE (Internet Explorer) and other methods doesn't support + symbol in the URL. THANKS @community wiki

@Paul Sweatte 2012-08-28 00:27:41


Firefox 44+, Opera 36+, Edge 17+, Safari 10.3+ and Chrome 49+ support the URLSearchParams API:

There is a google-suggested URLSearchParams polyfill for the stable versions of IE.

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

You can use it on location:

let params = new URLSearchParams(;


let params = (new URL(location)).searchParams;

Or of course on any URL:

let url = new URL('');
let params = new URLSearchParams(;

You can get params also using a shorthand .searchParams property on the URL object, like this:

let params = new URL('').searchParams;
params.get('foo'); // "1"
params.get('bar'); // "2" 

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) {}.

A reference implementation and a sample page are available for auditing and testing.

@Nakilon 2017-03-10 19:21:08

Those two downvoters probably missed (like I just did) the fact that you have to use .get instead of just .

@Jason C 2017-06-19 23:48:41

You don't actually need to slice(1) on .search, you can use it directly. URLSearchParams can handle the leading ?.

@Melab 2017-08-04 22:19:04

URLSearchParams is no good because it doesn't return the actual values of a URL's parameters.

@shah 2017-10-21 00:58:16

This new URL('') is not working for android url file:///android_asset/...

@Damon 2018-02-16 21:20:47

@Melab it's still good in that it provides a simple API for all the weird regexing in the other answers here. But it also weirds me out that id doesn't do by default and that there's no way to update the current url included.

@Artem Barger 2009-05-23 08:35:46

Update: Sep-2018

You can use URLSearchParams which is simple and has decent (but not complete) browser support.

const urlParams = new URLSearchParams(;
const myParam = urlParams.get('myParam');


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, ' '));


// 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.
NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, add 'i' modifier to RegExp

This is an update based on the new URLSearchParams specs to achieve the same result more succinctly. See answer titled "URLSearchParams" below.

@dan_nl 2010-04-23 06:09:55

on the name.replace line you've got a replace that seems to be escaping the \ and ] - is that correct or should it be "\\]" because ] does not need to be escaped?

@Ed James 2010-05-21 09:41:39

might be nice to use the jQuery data() function to cache the results for repeated access instead of re-doing the parsing every time...

@Artem Barger 2010-05-23 07:15:34

might be nice, but in this context there is no point do so, since then you will need to handle stale data check and so on...

@dpp 2011-07-09 06:34:57

How does this function handle The value of field x is ambiguous.

@Artem Barger 2011-08-16 11:28:21

@Kyralessa, my point was to show that you do not need to use frameworks to achieve the goal. But you welcome to rewrite and produce jQuery plugin, btw why not Dojo or ExtJS?

@hurrymaplelad 2011-10-07 08:47:02

this also doesn't handle multi-valued keys, which are also perfectly legal.

@Ry- 2011-10-22 23:57:19

Why would you use a regular expression for this?

@gilly3 2011-12-09 22:28: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 instead of location.href. An answer with over 400 upvotes should account for these details.

@Jamey 2012-04-25 21:07:57

We borrowed this, but added a param to ignore case on the key name. So the line where you create the regex becomes var regex = new RegExp(regexS, (ignoreCase ? "i" : undefined));

@Behrang Saeedzadeh 2012-10-29 05:55:09

What's the point of "\\\]"? Why not just \\ ]? (Stackoverflow does not let me write \\ in a code block).

@Tobin Rysenga 2013-01-04 05:07:03

This code for whatever reason does not function on the latest Firefox - works fine in IE9 and Chrome. The answer below however worked in all 3.

@usr 2013-03-10 21:06:20

How can we ever be sure that this is correct? The fact that I can't find a bad test case doesn't mean there is none. This is a security issue after all! For gods sake, call a well tested standard library function.

@Ph0en1x 2013-04-13 14:42:38

I think that answer could be extended for the case, when some params placed after # sign. I modify the method for that case - see my answer

@gztomas 2013-05-30 14:15:06

You don't need jQuery for that or any other purpose. You just don't actually NEED it.

@Eric 2013-06-02 00:48:08

I was unable to get this working for me when using hashes. I had to check for history.pushState and if not available use '?' + location.hash.split('?')[1] for the search string. Hope that helps someone else out.

@iRaS 2013-07-04 11:57:56

I'm writing unit tests and that is too much of logical algorythm in there. I would have to write a test to test the test... let's say jQuery is working then I can use the jQuery method to test a query string.. and if it is not working correct a jQuery bug report will do the trick.. just my two cents..

@Rup 2013-08-01 10:43:29

@BhargavPanchal I think that's a bad edit: you're no longer properly escaping the value you're searching for (paramName in your code - the escaping is applied to name) and you're not actually searching name either: it's hard-coded to use I'm going to revert.

@David Fariña 2013-09-27 13:12:42

sorry but when you explode the string and then explode its parts it works for everything that may come plus its even less code

@Sahil Jariwala 2013-09-29 11:56:39

This might help you:… you can create querystring and pass parameters using the javascript function as described in this link.

@Dorian 2014-02-12 18:17:25

It doesn't work with ?b for instance (without '=') because of the = in the Regexp, and when removing it, it matchs ?return for the r param. Here is my solution using Underscore.js

@vignesh.D 2014-02-13 13:10:41

There are so many things wrong with this answer. I feel like I've left StackOverflow and wandered into the PHP Annotated Manual

@Yannis Dran 2014-02-21 11:24:07

As a beginner I am really confused by this answer. Question is about Jquery and answerer says "no need for Jquery, you can use Vanilla Js". Hello? Do you mean that I have to ditch my Jquery script call and other Jquery functions and call another script as suggested by Vanilla team: <script src="path/to/vanilla.js"></script>?? Exactly what @TomHeard said. After doing some further research I discovered the source: So, I guess it is not vanilla, just either the answerer likes the word "vanilla" instead of "pure" or I am really confused.

@Tom Heard 2014-02-24 01:32:35

@YannisDran I highly suspect that the answerer meant pure javascript, and not some javascript variant or library called Vanilla javascript.

@ErikE 2014-05-22 19:55:12

Injecting an unscrubbed/untranslated user-supplied value into a regex... awful.

@Rituraj ratan 2014-08-13 17:28:50

@smohadjer 2015-02-13 09:19:33

jshint throws error Bad or unnecessary escaping on first line of function!

@Pian0_M4n 2015-04-16 20:20:24

May often return null. Change to window.location.hash

@Sameer Kazi 2015-04-17 03:27:51

@enb081 2015-04-29 14:26:48

Basically everything that can be done with jQuery, it can be done with pure JavaScript, too. What is this all about?!

@pdorgambide 2015-05-11 19:57:29

An alternative that parser the full query string as object:…

@scooter-dangle 2015-11-11 19:27:18

@Kip and @Dorian, for a query string like ?a=1&b&c=2, it doesn't make sense to consider b, at least according to the W3C recommendation that defines a query string as consisting of field=value pairs. That would be like expecting b to be listed as a null-valued property of an object defined with var obj = { a: 1, c: 2 } // b.

@Kip 2015-11-11 20:06:38

@scooter-dangle Not sure what you mean. You could represent it as obj={ a:1, b:'', c:2 } or obj={ a:1, b:null, c:2 }. I would prefer the former, but in either case, the important thing is that obj.b is not undefined. Another edge case ?a=1&b=&c=2. See also:…

@scooter-dangle 2015-11-12 19:58:12

@Kip, yeah, you could represent an object in general like that, but I meant that a field without a value isn't described at all by the W3C recommendation. It would be a custom extension on top of a recognized format. Perhaps a better analogy to a js object creation would be for obj = { a: 1, b, c: 2 } to create an object where b is nil. That would work if the definition provided for that, but since it doesn't, it's a custom extension and the behavior shouldn't have to be implemented for a general function parsing that data structure, right?

@zygimantus 2016-04-11 07:14:27

It does not work with capital letters, etc.,, and you'll get just Ex.

@Shubham Kumar 2016-05-09 06:17:37

Here's simple regex code I'm using :…

@Hlawuleka MAS 2016-08-24 09:49:50

The regex also does not handle query string that have HTML entities such as "foo=john&amp;Marry".

@andi 2016-08-25 15:23:56

@HlawuM - &amp; would have to be encoded there. If you wanted foo to equal "john&Marry", you'd write it like foo=john%26Marry.

@andi 2016-08-25 15:28:47

HOWEVER, I think it is valid to write ?foo=john&amp;bar=mary - that should function the same as if you wrote ?foo=john&bar=mary. This function doesn't return the proper value for bar though because of that. I think you'd have to do a global replace of '&amp;'->'&' before executing the regex.

@Hlawuleka MAS 2016-08-25 19:47:01

I think it's mostly best to use Hexacodes when writing regex, e.g instead of the explicit & symbol you could use \26.... That would also resolve what I pointed out.

@KingRider 2017-01-06 17:53:48

Not work params preview[theme_id] is only work URLSearchParams .. i not know is what motive. Where wrong. I think [ ]

@akd 2017-06-01 12:09:22

it would be nice to ignore case for names. toLowerCase() to href I guess

@dekdev 2017-06-21 15:50:24

@Levi Fuller 2017-07-11 19:58:37

This is most definitely not a robust solution: For instance given a URL of localhost:5000/account/… results in /connect/authorize/login?client_id=mvc which missed much

@surfbird0713 2017-09-06 21:01:03

URLSearchParams is not supported by edge, or on mobile in safari.

@FlameStorm 2018-07-18 12:21:52

This not answers about array and object params, like[]=2&arr[]=15&obj[a]=some&obj[b]=other. PHP automatically handle such params. What about JavaScript parsing this ones? Added here as new Q&A.

@nuno 2018-10-16 09:46:59

You can use let myParam = urlParams.getAll('myParam') to retrieve all the values associated with a given search parameter.

@gattsbr 2019-02-28 16:14:29

Have had this in a working thing for a long time. The pure javascript worked, and still works. The new URLSearchParams ends up returning null.

@saurabh 2019-09-06 00:26:34

No doubt the updated logic with class URLSearchParams is best.. but not yet compatible even with latest versions of IE. Thus, I'd request all to think before its use if the scope of your development includes IE or test on other browsers as well to avoid future issues.

@bluejayke 2020-06-02 06:25:30

also a simple one liner Object.fromEntries("&").map(x => x.split("=")) )

@IT ppl 2012-05-24 08:18:40

This one works fine

function getQuerystring(key) {
    var query =;
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == key) {
            return pair[1];

taken from here

@Rup 2012-05-24 08:44:42

You probably at least want to call decodeUriComponent on the pair[1] before you return it, if not replace pluses with spaces first as in all the other solutions here. Some of the other solutions also prefer a limit of 2 parts on the split = to be more lenient in accepting input.

@IT ppl 2012-05-24 09:22:08

@Rup you are right...actually in my code it'll always be a number rather than any special characters, so missed ...

@Roc Boronat 2019-11-25 01:51:16

Thanks for it! It's the only method supported by the Kindle's Experimental Browser. Freak project here! :·)

@Anatoly Mironov 2012-01-10 23:36:08

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 the 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 = {},
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q =;

        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.

@mhenry1384 2014-09-23 17:38:03

Looks like window.location.getParameter() has been removed from Chrome.

@Eneko Alonso 2011-05-03 23:59:19

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

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

@dogonaroof 2019-02-08 11:51:12

I wasn't wanting to use Regex and went with this solution. I find it works rather nicely. Thanks!

@nkh 2013-05-14 12:47:10

If you are using Browserify, you can use the url module from Node.js:

var url = require('url');

url.parse('', true).query;

// returns { "bob": "123" }

Further reading: URL Node.js v0.12.2 Manual & Documentation

EDIT: You can use URL interface, its quite widely adopted in almost all the new browser and if the code is going to run on an old browser you can use a polyfill like this one. Here's a code example on how to use URL interface to get query parameters (aka search parameters)

const url = new URL('');

You can also use URLSearchParams for it, here's an example from MDN to do it with URLSearchParams:

var paramsString = "q=URLUtils.searchParams&topic=api";
var searchParams = new URLSearchParams(paramsString);

//Iterate the search parameters.
for (let p of searchParams) {

searchParams.has("topic") === true; // true
searchParams.get("topic") === "api"; // true
searchParams.getAll("topic"); // ["api"]
searchParams.get("foo") === null; // true
searchParams.append("topic", "webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
searchParams.set("topic", "More webdev");
searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
searchParams.toString(); // "q=URLUtils.searchParams"

@andrezsanchez 2014-09-12 18:23:10

The documentation for the url module's API is here:

@Andrew Grothe 2015-07-13 23:22:18

This is nice for nw.js development. Browserify isn't even needed as most node modules work as is in a nw.js window. I've tested this code and works like a charm without any modification.

@Baran Emre 2019-07-17 09:27:22

OHH this is awesome! URLSearchParams works perfect. Many thanks!

@TheWhiteLlama 2019-09-29 21:46:53

should probably be the best voted, no hassle with custom functions and additional libraries. It also seems to be mostly adopted by the browsers 2019.

@BrunoLM 2010-10-04 12:53:04

ES2015 (ES6)

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
        : {}

Without jQuery

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.length == 1)
            b[p[0]] = "";
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    return b;

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. It does not work because some variables are undefined.

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 then they store the value of d, otherwise they 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(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
            let param = paramsArray[i]
                .split('=', 2);
            if (param.length !== 2)
            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        return params;


//Get a param
//This outputs something like...

//Get all params as object
//This outputs something like...
//Object { param: "val", param2: "val" }

//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object

//Convert object into string suitable for url a querystring (Requires jQuery)
//This outputs something like...

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
history.pushState({}, '', "?" + $.param($.QueryString));

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

@Andy E 2010-10-04 13:07:55

This is also a nice approach, string splitting instead of using regular expressions. There's a few things worth pointing out, though :-) 1. unescape is a deprecated function and is replaced with decodeURIComponent(), note that neither of these functions will correctly decode a + to a space character. 2. You should declare the result as an object, rather than an array because JavaScript doesn't have associative arrays, per se, and the array you declare is treated as an object by assigning named properties to it anyway.

@zachleat 2011-02-23 13:55:20

Curious why you'd make this a jQuery plugin when it doesn't have any jQuery specific code?

@BrunoLM 2011-02-23 13:57:13

@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.

@patridge 2011-06-15 17:48:57

Here is the jQuery version tweaked to pass JSLint (at least the semi-moving target of on 2011-06-15). Mostly just moving things around to appease The Crockford.

@Andy E 2011-10-04 11:06:35

@BrunoLM: taking a look at your jsperf, I noticed that it's not particularly a fair test as both methods attack the problem from different angles. The accepted solution, whilst generally inefficient, would prove to be more efficient if only accessing one parameter from the query string. For a fair "split vs regex" comparison, I compared your code to the code in my answer and split came out consistently slower in Opera, Chrome and IE. In Firefox, the difference between the two was negligible. The jsperf is here.

@Andy E 2011-10-04 11:09:06

It's also worth mentioning that I slightly altered your code in the perf test to properly decode the parameter name as your current code doesn't.

@Jason Sebring 2012-03-25 19:34:27

Another thing to consider about performance is user experience (bandwidth and also maintenance). If you don't have a realistic case where you will be calling this method more than 1000 times on a page, the shortest and simplest code would be preferable. Just keep that in mind when doing these perf tests. It has to intuitively make sense. I would say DOM manipulation and graphics for games are more inline with these types of tests in significance as an example.

@MetaGuru 2012-04-24 18:55:49

Trying to implement your plugin gives me an error on the last line: "Uncaught SyntaxError: Unexpected token )" even though I copied it exactly and all of the parenthesis have a match.

@user960567 2012-11-21 07:54:22

Your plugin is failing in Latest version of firefox

@styfle 2013-03-01 18:47:06

I don't think you need this line: if (a == "") return {};. The split function returns an array and I don't see the purpose of comparing an array to the empty string. Unless you think [] == "" which is useless because the for loop will check the length of the array.

@rtpHarry 2013-08-02 16:11:18

used this plugin before with great success but it seems its not compatible with the newer versions of jQuery (tested in 1.9.1) - I just get $.QueryString() is not a fuction

@LarsH 2013-10-14 14:16:47

Does this handle parameters that have no =? I don't think so. E.g. Ideally, qs['large'] would tell me whether the large parameter is present or not, but it doesn't.

@Andre Figueiredo 2013-11-28 12:00:04

What about the case where I can have a expected query string or not, like in a Search page? eg: $.QueryString['codList'].toArray() pass on,2,3, but fails on

@BrunoLM 2013-11-28 12:04:08

@AndréFigueiredo if you attempt to retrieve a value that doesn't exist it is going to return undefined, so you have to check if the value exists. Or do something like ($.QueryString['codList'] || "").toArray()

@Makaze 2014-12-22 21:33:17

Regex method is considerably faster in all but Firefox. Best method to use IMO.

@Shawn Kovac 2015-05-19 22:07:03

the accepted answer and this 'split' method one does not work when a querystring value is 'a=b' such as: "?one=a=b&two=2" because var p=a[i].split('=', 2); will truncate the returned array to two items, not return an array like ['one', 'a=b']. i fixed it in my code, but this question is locked, so i can't post a working answer.

@Dan Dascalescu 2015-06-09 11:28:52

As @BenjaminGruenbaum joked, I too don't quite see the point in benchmarking the performance of URL parsing. If this was made into an isomorphic JavaScript module that could be called from Node to, say, parse logs, then yes. But using it to extract URL parameters from window.location makes any performance concerns moot, given that the client navigating to the URL is far, far more expensive.

@thdoan 2016-01-15 19:11:27

@BrunoLM there are a few issues with your jsperf: (1) you left out the leading "?" in your test string, so the split method is missing substr(1), (2) the regex method should be matching against the test string, not window.location.href, and (3) the regex method you used is not the same as the one in the chosen answer. Once you fix all three issues, then the regex method ends up faster:

@user1228 2017-05-05 15:25:24

I like your version, but it doesn't work with hash urls--here's a small tweak that handles them both (possibly, haven't re-tested with a non-hash url, but it passes muh personal code review) ( || window.location.hash.split('?')[1]).split('&')

@Christiaan Westerbeek 2017-11-29 13:13:02

Shouldn't the key be decoded too? For example in the ES6 solution that line could read params[decodeURIComponent(key.replace(/\+/g, ' '))] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : ''; which of course begs for a reused decoder function (for key and value)

@Alexander Goncharov 2018-01-04 01:21:22

Maybe var parseQuery = (query) => query.split('&').reduce(function(acc, val){ var pair = val.split('='); acc[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || ''); return acc; },{});

@eel ghEEz 2018-04-04 22:05:58

The javascript split ignores the tail when values have the equal sign =. So I added a Java-like split to Bruno's solution,

@Roland 2018-11-12 17:41:41

this answer should have been split into 4 separate answers. The second 'Google' method does not work: a has not been defined. Neither does h, and a bunch of others. Why use obfuscated code? Is the code that we regularly have to maintain not hard enough ?

@BrunoLM 2018-11-12 17:48:24

@Roland I extracted from Google's search page, I don't have access to the unminified version they use at Google. It doesn't run because it's out of context.

@Tugrul Emre Atalay 2020-01-26 09:34:09

If there is "=" in query value, this code works wrong.

@Martin Borthiry 2012-09-03 21:08:41

Just use two splits:

function get(n) {
    var half = + '=')[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 ='&' + n + '=')[1];
    if (!half) half ='?' + 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.

Or if you have control of the querystring and can guarantee that a value you are trying to get will never contain any URL encoded characters (having these in a value would be a bad idea) - you can use the following slightly more simplified and readable version of the 1st option:

    function getQueryStringValueByName(name) {
        var queryStringFromStartOfValue = + '=')[1];
         return queryStringFromStartOfValue !== undefined ? queryStringFromStartOfValue.split('&')[0] : null;

@Rup 2012-09-04 11:46:10

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.

@Martin Borthiry 2013-05-16 17:57:49

However, if you know the parameter name are expecting, This will be the faster approach.

@philh 2014-06-17 15:03:54

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.

@niutech 2014-09-01 22:54:14

Cool! I made a one-liner: function get(param){return decodeURIComponent(('=')[1]||'')‌​.split('&')[0])}

@divillysausages 2015-01-13 22:54:28

I had to change the second line to return half !== undefined ? decodeURIComponent(half[1].split('&')[0]) : null; to get it to work

@Campbeln 2014-05-01 03:51:40

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...


...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 =, //# suggested: q = decodeURIComponent(,
        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) {, 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]);
      [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 {[k], v); }

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

@Mike Clark 2015-02-03 10:10:05

For getting the query string values you can use this "GetParameterValues" function. In this you just have to pass the query stirng parameter name and it'll return you the value $(document).ready(function () { var bid = GetParameterValues('token'); }); function GetParameterValues(param) { var url = decodeURIComponent(window.location.href); url = url.slice(url.indexOf('?') + 1).split('&'); for (var i = 0; i < url.length; i++) { var urlparam = url[i].split('='); if (urlparam[0] == param) { return urlparam[1]; } }

@Vladislav Dimitrov 2017-07-27 08:36:46

I've been using this for a while now, and it's been great so far. Except for handling urlencoded arrays. Using q = decodeURIComponent(, helps it do that too.

@Qwerty 2014-01-16 03:20:35


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

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

//using ES6   (23 characters cooler)
var qd = {};
if (`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
var qd = {};
if ("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit

What is all this code...
"null-coalescing", short-circuit evaluation
ES6 Destructuring assignments, Arrow functions, Template strings

> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, " test.asp?name=ståle&car=saab"]

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

Read more... about the Vanilla JavaScript solution.

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

Easiest (dummy) solution

var queryDict = {};"&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
  • Handles empty keys correctly.
  • Overrides multi-keys with last value found.
> 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 = {};"&").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 = {};"&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", " test.asp?name=ståle&car=saab"]

From comments

*!!! 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);

If the querystring is empty ( == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if ("&").forEach(...)

@Pavel Nikolov 2014-01-16 21:03:40

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.

@Qwerty 2014-01-16 21:20:10

@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 2014-03-21 09:06:07

@katsh Yes indeed, it works in >=IE9, however, you can teach your javascript processor array.forEach() by injecting certain code at the beginning of your script. see Polyfill…

@Qwerty 2014-04-26 23:58:04

@katsh also it's not problem to rewrite it to normal for loop, but the solution wouldn't be this elegant :)

@Casey 2015-02-06 10:04:07

Flattened out a bit for readability, made into a function, and re-used split call: function parseQueryString() { var qd = {};"&").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; }

@Dan Dascalescu 2015-06-09 11:55:06

Just curious, why the trailing comma when creating the array of one element? CC @Casey.

@Qwerty 2015-06-09 12:29:27

@DanDascalescu Haha, nice catch. :P That's my fault and I left it there mistakenly after I was done experimenting with the most elegant form.

@loop 2015-06-24 12:07:44

decodeDocumentURI(undefined) returns "undefined" instead of undefined. A functional but not very elegant patch: var qd = {};"&").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] })

@Qwerty 2015-07-14 17:29:40

@loop Thank you! fixed using v = v && decodeURIComponent(v)

@Isochronous 2016-02-10 21:00:22

@Querty, wouldn't that be v = s && decodeURIComponent(v) ? Your version will never execute decodeURIComponent.

@Isochronous 2016-02-10 21:28:23

@Querty, whoops, I meant v = k && decodeURIComponent(v).

@Qwerty 2016-02-11 16:12:08

@Isochronous Are you sure? The conjunction runs when v evaluates to true, which is the case when v has a value (e.g. is not undefined). Also, it's Qwerty, not Querty :D (you are actually not the first)

@Qwerty 2016-02-11 16:39:21

@Isochronous The previous version was v = item.split("=")[1]; v = v && decodeURIComponent(v);, now it's var s = item.split("="), v = s[1] && decodeURIComponent(s[1]); The point of it was that when the split[1] returned undefined, then decodeURIComponent(undefined) returned string "undefined", which is wrong.

@Triynko 2016-10-24 16:31:46

Why is this not decoding the 'name' of the value as well? It may very well have encoded characters.

@Qwerty 2016-10-24 16:43:49

@Triynko It may, but it doesn't make much sense. You should use English standard letters for variable names anyway. But you of course can wrap both splits within their decodeURIComponent().

@Brian S 2017-03-22 19:13:15

I like your solution. However, when I try it on a page that happens to have no query params, qd == {'':[undefined]}, which is less than desirable. My solution checks that is non-empty before running your code, so the dictionary is empty if there are no params.

@Roi 2013-03-29 00:59:07

A very lightweight jQuery method:

var qs ='?','').split('&'),
    request = {};
$.each(qs, function(i,v) {
    var initial, pair = v.split('=');
    if(initial = request[pair[0]]){
        if(!$.isArray(initial)) {
            request[pair[0]] = [initial]
    } else {
        request[pair[0]] = pair[1];

And to alert, for example ?q


@Rup 2013-04-02 08:48:39

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.

@Roi 2013-05-13 20:55:59

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

@Vadim 2010-11-16 09:55:08

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:




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]] = ''
        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

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

        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] = []
        } else {
            if (typeof(obj[k]) != 'object') obj[k] = {}
            obj[k][bpv] = v
    return obj;


@brauliobo 2019-09-19 18:11:50

nice but doesnt deal with the case filters[topic][]=list

@user981090 2012-01-05 00:26:07

Try this:

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

Then call it like so:

if( != "")"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

@user2579312 2013-09-07 08:37:17

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

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

@Rup 2013-09-08 22:40:05

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).

@JoshYates1980 2017-06-07 19:02:39

but what if you have (MVC routing)

@Anoop 2011-10-16 18:38:02

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 =;
       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){
               return true;
              return false;
       this.getValue = function(query){
               return qsParm[query];
           throw "URL does not contain query "+ query;

@Ankit_Shah55 2013-09-13 17:29:21

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

Use gV(para_name) function to retrieve its value

a=a.replace(a.charAt(0),""); //Removes '?'

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

@Robert Bolton 2013-05-17 02:14:15

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;

@farnoush resa 2013-07-13 08:38:29

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 ='?', '').split('&');
for (var i = 0; i < querystring.length; i++) {
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    queryObj[name] = value;

@Rup 2013-07-15 10:37:10

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 2013-07-17 08:31:10

Dar Lessons has now released 1.1 which fixes the script injection attack.

@krisrak 2014-04-16 18:16:32

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

@Rup 2014-04-19 12:33:15

That's basically the same as the top answer though, less some some of the unescaping, just put on the String.prototype.

@krisrak 2014-04-19 15:44:13

@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

@Dorian 2014-02-12 18:19:29

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 =^\?/, '');
  params ='&'), function(s) {
    return s.split('=');

  param_value =, function(s) {
    return s.first === name;

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

@Rup 2014-02-13 16:07:21

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.

@Dorian 2014-02-13 17:12:53

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.

@Vladimir Kornea 2014-05-30 02:17:09

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:
 *                               (undefined)
 *                              (undefined)
 *                       (empty string)
 *                      (empty string)
 *                     (the string '0')
 *    (the string 'override')
 * Origin:
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 ||
        reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
        var queryString = reducedUrl.split('?')[1]
        if (!queryString) {
            if ('=') !== 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.

@Rup 2014-06-02 07:22:22

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.)

@Vladimir Kornea 2014-11-18 11:43:19

Parameter names should never need decoding.

@Rup 2014-11-18 12:09:38

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.

@Sudar 2015-04-01 07:19:07

The solution is good, but why no semicolon at the end of statements?

@Vladimir Kornea 2015-04-01 12:04:11

@Sudar Because there is no reason to have them. Most people always include them just because they've always seen other people include them and because other languages require them; often they are wrongly regarded as required in JavaScript as well, which sometimes causes baffling problems. Doing things for no reason is generally misleading; JavaScript is not C++ or PHP. Look up defensive semicolon.

@NiCk Newman 2015-07-13 16:14:35

'Amazing how many overly complicated and incomplete solutions are posted here' Lol, the irony..

@Sagiv Ofek 2012-02-20 14:00:00

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[hash[0]] = hash[1];
    return vars[key];

Call it from anywhere in the JavaScript code:

var result = qs('someKey');

@Qwerty 2014-01-16 14:52:01

I think you are doing something similar as me, but I think my approach is MUCH simplier

@ErikE 2017-01-19 02:08:18

Let me introduce you to (drumroll please)!

@skaurus 2011-08-18 10:45:21

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

var url = '';
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;

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 results will be same. But with url Bruno's solution returns an object without keys, while mine returns an object with key param and undefined value.

@Mic 2011-03-14 10:13:40

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 =,
    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 you can get their value later in your code as search.param1 and search.param2.

@acjay 2013-11-20 15:17:59

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

_.object('&').map(function (val) { return val.split('='); }));

@Rup 2013-11-20 15:32:31

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.

@acjay 2013-11-21 06:18:31

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.

@David Fregoli 2014-01-07 14:46:07

this is what I use to make a key value object of the query parameters: _.chain('&')).invoke‌​('split', '=').object().value()

@Pushkraj 2013-07-23 13:00:05


  $(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 =;

          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.

@Rup 2013-07-23 13:10:55

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?

@Pushkraj 2013-07-23 13:14:37

@soheil bijavar 2013-07-10 09:27:37

See this post or use this:

<script type="text/javascript" language="javascript">
        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  =;

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

        if (urlParams["q1"] === 1)
            return 1;

@Rup 2013-07-10 11:35:53

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 2013-07-10 11:42:22

... although it's the same as Andy E's solution above.

@Peter Mortensen 2016-07-24 14:08:44

The link is broken.

@Mikhus 2013-04-19 07:18:16

I did a small URL library for my needs here:

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

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


@Rup 2013-04-19 09:00:55

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.

@Mikhus 2013-04-19 09:28:15

Why decoding in that way explained here: Actually, I've took the code for that idea from there, what is stated in a top-level comment at my script

@brauliobo 2019-09-19 18:19:21

also doesnt't support object arrays like filters[topic][]=list

@Ph0en1x 2013-04-13 14:37:07

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;

@Rup 2013-04-22 12:48:54

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.

@Ph0en1x 2013-04-22 14:15:30

Yes, I know. But in my app i integrate 3rd party js navigation, which have some parameters after hash sign.

@etlds 2014-06-26 14:51:20

For example, in the Google search page, the searching query is followed by the hash sign '#'.

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

95 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6845072 View
  • 8423 Score
  • 95 Answer
  • Tags:   javascript arrays

67 Answered Questions

[SOLVED] How to replace all occurrences of a string?

53 Answered Questions

81 Answered Questions

[SOLVED] How can I convert a string to boolean in JavaScript?

  • 2008-11-05 00:13:08
  • Kevin
  • 2054823 View
  • 2591 Score
  • 81 Answer
  • Tags:   javascript

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 750434 View
  • 2793 Score
  • 42 Answer
  • Tags:   javascript jquery

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

3 Answered Questions

39 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

Sponsored Content