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?

upvote
  flag
I use the plugin getUrlParam described in jQuery-Plugin – getUrlParam (version 2). – coma
upvote
  flag
I like dojo's queryToObject. The function could easily be plucked from the framework if you're on a diet. – hurrymaplelad
69 upvote
  flag
A plain javascript solution without RegEx: css-tricks.com/snippets/javascript/get-url-variables – Lorenzo Polidori
6 upvote
  flag
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
1 upvote
  flag
possible duplicate of JavaScript query string – user456814
upvote
  flag
I have added a single-line solution using vanilla javascript //allinonescript.com/a/21152762/985454 Be sure to check it out! – Qwerty
4 upvote
  flag
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
upvote
  flag
here is a jQuery plugin I use, github.com/huochunpeng/jquery-urlparam – huocp

73 Answers 11

If you're using jQuery, you can use a library, such as jQuery BBQ: Back Button & Query Library.

...jQuery BBQ provides a full .deparam() method, along with both hash state management, and fragment / query string parse and merge utility methods.

Edit: Adding Deparam Example:

 var DeparamExample = function() {
            var params = $.deparam.querystring();

            //nameofparam is the name of a param from url
            //code below will get param if ajax refresh with hash
            if (typeof params.nameofparam == 'undefined') {
                params = jQuery.deparam.fragment(window.location.href);
            }
            
            if (typeof params.nameofparam != 'undefined') {
                var paramValue = params.nameofparam.toString();
                  
            }
        };

If you want to just use plain JavaScript, you could use...

var getParamValue = (function() {
    var params;
    var resetParams = function() {
            var query = window.location.search;
            var regex = /[?&;](.+?)=([^&;]+)/g;
            var match;

            params = {};

            if (query) {
                while (match = regex.exec(query)) {
                    params[match[1]] = decodeURIComponent(match[2]);
                }
            }    
        };

    window.addEventListener
    && window.addEventListener('popstate', resetParams);

    resetParams();

    return function(param) {
        return params.hasOwnProperty(param) ? params[param] : null;
    }

})();​

Because of the new HTML History API and specifically history.pushState() and history.replaceState(), the URL can change which will invalidate the cache of parameters and their values.

This version will update its internal cache of parameters each time the history changes.

up vote 6552 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.


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

4 upvote
  flag
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? – dan_nl
1 upvote
  flag
might be nice to use the jQuery data() function to cache the results for repeated access instead of re-doing the parsing every time... – Ed James
1 upvote
  flag
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... – Artem Barger
1068 upvote
  flag
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
115 upvote
  flag
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
5 upvote
  flag
@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? – Artem Barger
2 upvote
  flag
upvote
  flag
I've take it from some Javascript book a years ago, so not sure whenever your reference could be a original source. – Artem Barger
75 upvote
  flag
this also doesn't handle multi-valued keys, which are also perfectly legal. – hurrymaplelad
9 upvote
  flag
Why would you use a regular expression for this? – Ryan
25 upvote
  flag
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
1 upvote
  flag
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)); – Jamey
upvote
  flag
What's the point of "\\\]"? Why not just \\ ]? (Stackoverflow does not let me write \\ in a code block). – Behrang
1 upvote
  flag
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. – Tobin Rysenga
38 upvote
  flag
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
5 upvote
  flag
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. – usr
upvote
  flag
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 //allinonescript.com/a/15988938/1888017 – Ph0en1x
4 upvote
  flag
You don't need jQuery for that or any other purpose. You just don't actually NEED it. – gztomas
1 upvote
  flag
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. – Eric
upvote
  flag
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.. – iRaS
upvote
  flag
@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 location.search. I'm going to revert. – Rup
upvote
  flag
sorry but when you explode the string and then explode its parts it works for everything that may come plus its even less code – David Fariña
upvote
  flag
This might help you: frontend.citynamaste.com/2013/09/… you can create querystring and pass parameters using the javascript function as described in this link. – Sahil Jariwala
2 upvote
  flag
Would it be too much to ask that a JavaScript expert tweak the 2000+ upvote community wiki answer so that it passes JSLint? – Edward Brey
upvote
  flag
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 gist.github.com/Dorian/833b37d2c7b168b7e94c – Dorian
4 upvote
  flag
There are so many things wrong with this answer. I feel like I've left StackOverflow and wandered into the PHP Annotated Manual – vignesh.D
upvote
  flag
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: netlobo.com/url_query_string_javascript.html So, I guess it is not vanilla, just either the answerer likes the word "vanilla" instead of "pure" or I am really confused. – Yannis Dran
3 upvote
  flag
@YannisDran I highly suspect that the answerer meant pure javascript, and not some javascript variant or library called Vanilla javascript. – Tom Heard
2 upvote
  flag
Injecting an unscrubbed/untranslated user-supplied value into a regex... awful. – ErikE
1 upvote
  flag
@Cerin I'm with you, but which function are you talking about exactly? I can't find any built-in jQuery function to do this. Sorry if this is already answered here. The number of answers and comments is a bit overwhelming. – Mike Garcia
upvote
  flag
upvote
  flag
doesn't work in iframe – shorif2000
upvote
  flag
jQuery will at least take care of any cross-browser compatibility issues with the different JavaScript APIs. – Henry Heleine
upvote
  flag
I just want to get parameter and I also don't want to use JQuery in my tiny page. Pure and simple always are the best. Thank you again. – vudangngoc
upvote
  flag
jshint throws error Bad or unnecessary escaping on first line of function! – smohadjer
upvote
  flag
May often return null. Change location.search to window.location.hash – Pian0_M4n
upvote
  flag
upvote
  flag
Basically everything that can be done with jQuery, it can be done with pure JavaScript, too. What is this all about?! – enb081
upvote
  flag
An alternative that parser the full query string as object: stevenbenner.com/2010/03/… – pdorgambide
2 upvote
  flag
If you do not feel that your project needs JQuery, then do not use JQuery. If you feel that your project needs JQuery, use JQuery. If you were to include JQuery in your project only to parse out the query string like we are here, you would be a moron. If you include JQuery in your project and use it to do thousands of things, then you would be a moron for rewriting this function since its already in your project. JQuery is big, and odds are, you don't need it all. Only use what you need to use, and if you need it all, make sure you use it all. – WebWanderer
9 upvote
  flag
JQuery is like a rocket-ship. If your trying to get to the moon, JQuery will get you there. You can build a rocket-ship yourself, but that's a lot of hard and unnecessary work. With that being said, if your not trying to go to the moon, don't use a rocket-ship. If your trying to make a piece of toast, you don't need to install a rocket-ship in your kitchen to use the heat of the thrusters, yet you can write yourself a toaster. This answer is a toaster, and odds are, your making toast. If you already have a rocket-ship, look at the documentation to find out where the toaster is. – WebWanderer
upvote
  flag
@bonez not solution for a iframe ? – Kiquenet
upvote
  flag
I just built this. Send in a querystring string and it will return a JSON object. It takes a second param as well for pull out a value. Also works with hashes. Example: JSON.qs(window.location.search, 'page') JSON.qs = function(str, x){ try{ var obj = JSON.parse('{"' + str.replace(/[\?#]/,"").replace(/&/ig,"\",\"").replace(/=/ig‌​, "\":\"") + "\"}"); if(typeof x != 'undefined'){ return obj[x]; } else{ return obj; } }catch(e){} }; – Sefi Grossman
upvote
  flag
If I want to pass an object I can do with this too ? – PRVS
upvote
  flag
@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. – scooter-dangle
upvote
  flag
@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: //allinonescript.com/questions/4557387/… – Kip
upvote
  flag
@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? – scooter-dangle
1 upvote
  flag
@ArtemBarger I intend to use this answer without attribution assuming that is ok. (I suppose it is fairly rudimentary anyway) . I trust you are fine with this – D.Tate
upvote
  flag
I just Love pure java-script and if there is a way to do things without having to include the jquery file, why don't you go for it – Salam El-Banna
upvote
  flag
It does not work with capital letters, etc., https://www.test.com/test?date=2015-03-10&text=Example, and you'll get just Ex. – zygimantus
upvote
  flag
jQuery has been done in pure javascript, too. – Kazim Zaidi
upvote
  flag
Here's simple regex code I'm using : mycodingtricks.com/snippets/javascript/… – Shubham Kumar
upvote
  flag
I created a simple class e.g.: var id = new QueryValues(location.search).attr("id") gist.github.com/DJDaveMark/b2bd1045c03baccee6f744b8eb23d99d – DJDaveMark
upvote
  flag
The regex also does not handle query string that have HTML entities such as "foo=john&amp;Marry". – Hlawuleka MAS
upvote
  flag
@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
upvote
  flag
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. – andi
upvote
  flag
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. – Hlawuleka MAS
upvote
  flag
can someone write answer for getting an array – shorif2000
upvote
  flag
@Cerin I can't find any built-in jquery function to read query string values. Are you guys certain there is built-in jQuery function for this. Can some point where is it? – LP13
upvote
  flag
Not work params preview[theme_id] is only work URLSearchParams .. i not know is what motive. Where wrong. I think [ ] – KingRider
1 upvote
  flag
I made a function using for that is 35-120% faster than the others functions: araujo.cc/blog/como-ler-os-parametros-da-url-em-javascript.h‌​tml You can test performance in jsperf. – Arthur Araújo
upvote
  flag
it would be nice to ignore case for names. toLowerCase() to href I guess – akd
upvote
  flag
upvote
  flag
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 – Levi Fuller
upvote
  flag
I edited it to make it in 2 lines - 2017 version – Mr.Web
upvote
  flag
URLSearchParams is not supported by edge, or on mobile in safari. – surfbird0713
upvote
  flag
best answer to all time, lots of jealous haters – SuperUberDuper
upvote
  flag
Simple oneliner: var params = window.location.href.match(/\?(.+)/)[1].split('&').map(item => item.split("=").map(item2 => decodeURIComponent(item2))).reduce((accumulator,item) => (accumulator[item[0]] = item[1]) && accumulator,{}); – user3413723

Roshambo on snipplr.com has a simple script to achieve this described in Get URL Parameters with jQuery | Improved. With his script you also easily get to pull out just the parameters you want.

Here's the gist:

$.urlParam = function(name, url) {
    if (!url) {
     url = window.location.href;
    }
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if (!results) { 
        return undefined;
    }
    return results[1] || undefined;
}

Then just get your parameters from the query string.

So if the URL/query string was xyz.com/index.html?lang=de.

Just call var langval = $.urlParam('lang');, and you've got it.

UZBEKJON has a great blog post on this as well, Get URL parameters & values with jQuery.

13 upvote
  flag
with jQuery seems to mean to namespace the function to the jQuery object. Also, why is the invalid value 0? Sure, I could use strict equality check, but shouldn't it be null ? – alex
upvote
  flag
@TFennis Why should it be an exception? – alex
upvote
  flag
Agreed. It works just like a normal javascript variable reference that way (except maybe returning undefined would be more accurate). – Isochronous
2 upvote
  flag
check best answer here without regular expression //allinonescript.com/questions/19491336/… – Sameer Kazi
upvote
  flag
'name' is not properly escaped, it's just directly injected into the RegExp. This fails. Like others have said, it's unbelievable these answers are reinventing the wheel and getting so many votes, when this should be implemented in a well-tested library. – Triynko

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  = window.location.search.substring(1);

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

Example querystring:

?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

Result:

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

alert(urlParams["mode"]);
// -> "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!

10 upvote
  flag
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... – Nick Franceschina
95 upvote
  flag
@Nick: Anything after the hash resides in the window.location.hash property, which is separate from the window.location.search property. If the hash changes, it doesn't affect the querystring at all. – Andy E
1 upvote
  flag
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.) jsbin.com/amage4/edit – Jonathan
1 upvote
  flag
@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. – Andy E
upvote
  flag
@AndyE that's a really good idea. Here's some code that does it that way: gist.github.com/652644. – Jonathan
26 upvote
  flag
Don't forget the ; is a legal delimiter for GET key=value pairs. It is rare, but it takes 5 seconds to implement. – alex
3 upvote
  flag
location.search can change with HTML5's History API. Demo (Chrome and FF4 only). – Crescent Fresh
upvote
  flag
@Crescent Fresh: yeah, that's a pretty cool feature. I don't think this would cause any problems here, though - the developer would be changing the URL consciously and could re-run a small snippet like this whenever necessary. – Andy E
upvote
  flag
Yes the developer could. The point is it nullifies the statement "The query string will not change at all once the page is loaded". – Crescent Fresh
upvote
  flag
@Crescent: Ahh, I see what you were getting at now. No problem, I edited the post - thanks :-) – Andy E
1 upvote
  flag
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. – Dan Rosenstark
2 upvote
  flag
@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. – Andy E
1 upvote
  flag
@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 ;) – Dan Rosenstark
2 upvote
  flag
@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 ;-) – Andy E
1 upvote
  flag
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... – Dan Rosenstark
1 upvote
  flag
@Yar: indeed, in PHP it should be as easy as echo 'var params = '.json_encode($_GET).';' - example. So simple! – Andy E
upvote
  flag
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. – Damon
upvote
  flag
@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.. – Andy E
upvote
  flag
yeah i had the whole thing. didn't seem to make sense to me either. maybe some accidental crap or character encoding thing on my end. – Damon
4 upvote
  flag
+1 for correctly handling parameters which aren't followed by equals sign – Kip
upvote
  flag
For my current application this is my preferred solution, although it would have been nice if the example code was more readable. I've made an edit to the answer clarify what the code is doing. – joelmdev
upvote
  flag
@jm2: I appreciate your feedback and the time you took to edit the code, but I don't think your edits significantly improved readability because of the additional bulk. When I wrote the code, I did so with the intention of keeping the answer as concise as possible, and it's short enough and their are few enough variables for any experienced JS developer to figure out what's going on. Thanks anyway :-) – Andy E
3 upvote
  flag
@AndyE For production, you code is the way to go. For illustrating the answer to a question, a mostly minified function is not very descriptive. Just saying. – joelmdev
upvote
  flag
@jm2: And I was just saying that elongating variable names and uglifying the code doesn't really add much. – Andy E
1 upvote
  flag
This function will FAIL in Firefox, if you enter query with special characters (e.g. ?q=ö ), because of decodeURIComponent. (See bugzilla.mozilla.org/show_bug.cgi?id=580381) – Johannes Gerer
2 upvote
  flag
@JohannesGerer: I just tested in Firefox and the code here works perfectly. The bug you linked to seems unrelated, pertaining more to how decodeURIComponent will refuse to decode a string that is malformed due to incorrect encoding. – Andy E
upvote
  flag
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. – hsribei
upvote
  flag
@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. – Andy E
upvote
  flag
This is good but in my example, url: 'attr[]=309&attr[]=1772' .. only one attr: value is returned. – AndreeCrist
upvote
  flag
@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. – Andy E
3 upvote
  flag
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 / "/" / "?" ). – Matthew Gilliard
18 upvote
  flag
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) – craigts
upvote
  flag
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])}); – Matt Dell
1 upvote
  flag
I would use window.addEventListener("popstate", function(){}) instead of assignment – Maksym Kozlenko
upvote
  flag
@Maksym: so would I, but assignment is useful for conciseness in the answer. – Andy E
3 upvote
  flag
The regex is not working correctly, the first parameter is matching the all begining of the url: here is the fixed version: /([^?&=]+)=([^&]*)/g -> rubular.com/r/jnKzhVpo1b – Gomino
upvote
  flag
@AndyE Why is it even needed to attach to an event at all? Isn't the querystring always available anyway? – Stijn de Witt
upvote
  flag
Mmm thinking about it more.. Does the popstate event fire when we use the History API? If so, does that mean that this function can be used in conjunction with the History API without issues? – Stijn de Witt
upvote
  flag
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? – xr280xr
upvote
  flag
@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. – Andy E
upvote
  flag
check best answer here without regular expression //allinonescript.com/questions/19491336/… – Sameer Kazi
function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3
4 upvote
  flag
This is an interesting approach, returning an array containing values from the specified parameters. It does have at least one issue - not correctly URL decoding the values, and it would need to URL encode the parameter names used in match too. It will function on simple query strings in its present form though. ps don't forget to use the var keyword when declaring variables in for statements. – Andy E

ES2015 (ES6)

const getParams = query => {
  if (!query) {
    return { };
  }

  return (/^[?#]/.test(query) ? query.slice(1) : query)
    .split('&')
    .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]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

With an URL like ?topic=123&name=query+string, the following will return:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

Google method

Tearing Google's code I found the method they use: getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}

It is obfuscated, but it is understandable.

They start to look for parameters on the url from ? and also from the hash #. Then for each parameter they split in the equal sign b[f][p]("=") (which looks like indexOf, they use the position of the char to get the key/value). Having it split they check whether the parameter has a value or not, if it has they store the value of d, if not it just continue.

In the end the object d is returned, handling escaping and the + sign. This object is just like mine, it has the same behavior.


My method as a jQuery plugin

(function($) {
    $.QueryString = (function(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
        {
            let param = paramsArray[i]
                .split('=', 2);

            if (param.length !== 2)
                continue;

            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        }

        return params;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Usage

//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"

//Get all params as object
$.QueryString
//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)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue&param2=val"

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
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
upvote
  flag
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. – Andy E
upvote
  flag
@Andy: 1. I was having problems with IE so I had to change to unescape... Always IE... 2. Yea, you're right. I made this a while ago. I think it's time to fix it. :) – BrunoLM
6 upvote
  flag
@Andy: I've posted an improved version. What do you think of it? – BrunoLM
46 upvote
  flag
Curious why you'd make this a jQuery plugin when it doesn't have any jQuery specific code? – zachleat
48 upvote
  flag
@zachleat if you don't have a framework your functions will just get spread across your code. If you extend jQuery you will have a scope for your functions, it won't be floating around somewhere in your code. I think that is the only reason. – BrunoLM
upvote
  flag
For the benchmark, why don't you use jsPerf? – nyuszika7h
6 upvote
  flag
Here is the jQuery version tweaked to pass JSLint (at least the semi-moving target of JSLint.com on 2011-06-15). Mostly just moving things around to appease The Crockford. – patridge
upvote
  flag
It can get the query string values. It can set them. This is a beautiful plugin. Only...the one thing it doesn't seem to do is let me retrieve the modified querystring after I change a value or two. If it could do that as well, it would be my #1 favorite plugin of all time. – Kyralessa
1 upvote
  flag
@Kyralessa just do $.param($.QueryString) – Alex Turpin
1 upvote
  flag
@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
upvote
  flag
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. – Andy E
upvote
  flag
This doesn't work with hashbag urls. "/#!/" – Donny V.
4 upvote
  flag
The Google method returns an error : a is not defined – MaxiWheat
upvote
  flag
@MaxiWheat it is just a piece of the code which I extracted from Google js file. To run this method you need a much larger context, or do necessary changes to run. – BrunoLM
1 upvote
  flag
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. – Jason Sebring
upvote
  flag
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. – BigOmega
upvote
  flag
Your plugin is failing in Latest version of firefox – user960567
1 upvote
  flag
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. – styfle
upvote
  flag
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 – rtpHarry
26 upvote
  flag
Thank god for the benchmark. I'm writing code that needs to access a 50 thousand query string parameters and now I know which one to use. – Benjamin Gruenbaum
upvote
  flag
Does this handle parameters that have no =? I don't think so. E.g. http://foo.com/app?x=3&large. Ideally, qs['large'] would tell me whether the large parameter is present or not, but it doesn't. – LarsH
upvote
  flag
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 http://foo.com/?codList=1,2,3, but fails on http://foo.com/ – Andre Figueiredo
1 upvote
  flag
@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() – BrunoLM
upvote
  flag
How does window.location.search.substr(1).split('&') work? Doesn't search() require a parameter? – Sukima
1 upvote
  flag
upvote
  flag
Regex method is considerably faster in all but Firefox. Best method to use IMO. – Makaze
upvote
  flag
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. – Shawn Kovac
2 upvote
  flag
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. – Dan Dascalescu
upvote
  flag
@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: jsperf.com/querystring-with-javascript/40 – 10basetom
upvote
  flag
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.search.substr(1) || window.location.hash.split('?')[1]).split('&') – Will
upvote
  flag
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) – Christiaan Westerbeek

Here's my stab at making Andy E's excellent solution into a full fledged jQuery plugin:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);

The syntax is:

var someVar = $.getQueryString('myParam');

Best of both worlds!

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;

}
upvote
  flag
this is what I have been looking for. the support for [] kind of mappings. – Jimmy Ilenloa

Code golf:

var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
    var s = a[i].split("=");
    a[i]  = a[unescape(s[0])] = unescape(s[1]);
}

Display it!

for (i in a) {
    document.write(i + ":" + a[i] + "<br/>");   
};

On my Mac: test.htm?i=can&has=cheezburger displays

0:can
1:cheezburger
i:can
has:cheezburger
9 upvote
  flag
I love your answer, especially how compact the script is, but you should probably be using decodeURIComponent. See xkr.us/articles/javascript/encode-compare and //allinonescript.com/questions/619323/… – pluckyglen
upvote
  flag
Yes, unescape does NOT handle URIs correctly. – ErikE

Roshambo jQuery method wasn't taking care of decode URL

http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/

Just added that capability also while adding in the return statement

return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;

Now you can find the updated gist:

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

This is a function I created a while back and I'm quite happy with. It is not case sensitive - which is handy. Also, if the requested QS doesn't exist, it just returns an empty string.

I use a compressed version of this. I'm posting uncompressed for the novice types to better explain what's going on.

I'm sure this could be optimized or done differently to work faster, but it's always worked great for what I need.

Enjoy.

function getQSP(sName, sURL) {
    var theItmToRtn = "";
    var theSrchStrg = location.search;
    if (sURL) theSrchStrg = sURL;
    var sOrig = theSrchStrg;
    theSrchStrg = theSrchStrg.toUpperCase();
    sName = sName.toUpperCase();
    theSrchStrg = theSrchStrg.replace("?", "&") theSrchStrg = theSrchStrg + "&";
    var theSrchToken = "&" + sName + "=";
    if (theSrchStrg.indexOf(theSrchToken) != -1) {
        var theSrchTokenLth = theSrchToken.length;
        var theSrchTokenLocStart = theSrchStrg.indexOf(theSrchToken) + theSrchTokenLth;
        var theLocOfNextAndSign = theSrchStrg.indexOf("&", theSrchTokenLocStart);
        theItmToRtn = unescape(sOrig.substring(theSrchTokenLocStart, theLocOfNextAndSign));
    }
    return unescape(theItmToRtn);
}
33 upvote
  flag
you need to work on those var names – ajax333221
upvote
  flag
Also, better to go for decodeURI() or decodeURIComponent() instead of unescape(). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Adarsh Konchady

Improved version of Artem Barger's answer:

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

For more information on improvement see: http://james.padolsey.com/javascript/bujs-1-getparameterbyname/

21 upvote
  flag
If you wanted to shorten it a bit more, you could do away with the ternary conditional and replace it with a bit of short-circuitry on that last line - return match && decodeURIComponent(match[1].replace(/\+/g, ' '));. – Andy E
upvote
  flag
It returns null if the parameter isnt followed by '='. You could prepend if (!RegExp('[?&]'+name+'(&.*)?$').exec(window.location.search)‌​) return false; to make it return boolean false if the parameter isnt there at all. – commonpike
3 upvote
  flag
I wanted a solution that simply found the value of a query param key I specified. If it returned null or blank I'll handle that appropriately. Your solution worked the best after googling for a long time. – Brian
8 upvote
  flag
I would use the new prefix when creating the regex: var match = new RegExp('... – Patrick Berkeley
upvote
  flag
IE11 bug: IE decides to prepend the returned value with ascii character 8206 (hex: 200E - the "left-to-right character"). I wasted over 6 hours finding this! therapeutic venting .... to fix, tack to the end of the last line: .replace('\u200E', '') – JayRO-GreyBeard
upvote
  flag
In chrome on a mac at least (maybe other browsers too) the last value was getting a '/' appended. So I modified the regex to ignore it. var results = new RegExp('[\\?&]' + name + '=([^&#/]*)').exec(url); – CaseyB
upvote
  flag
anyone had issues in iphone safari. I got undefined value in return in some cases – user1371896

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.

Just another recommendation. The plugin Purl allows to retrieve all parts of URL, including anchor, host, etc.

It can be used with or without jQuery.

Usage is very simple and cool:

var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

However, as of Nov 11, 2014, Purl is no longer maintained and the author recommends using URI.js instead. The jQuery plugin is different in that it focuses on elements - for usage with strings, just use URI directly, with or without jQuery. Similar code would look as such, fuller docs here:

var url = new URI('http://allmarkedup.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'
5 upvote
  flag
This URL parser is ridiculously fat in file size.. – vsync
21 upvote
  flag
URL parsing isn't simple. – Dmitry Minkovsky
2 upvote
  flag
Seeing the RegEx engine for purl was created by RegEx Genius Steve Levithan... I'm gonna use this. – Eddie B
7 upvote
  flag
As of writing purl is no longer maintained and the previous maintainer suggests uri.js – Dan Pantry

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

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

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

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.

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

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

I like Ryan Phelan's solution. But I don't see any point of extending jQuery for that? There is no usage of jQuery functionality.

On other hand I like the built-in function in Google Chrome: window.location.getParameter.

So why not to use this? Okay, other browsers don't have. So let's create this function if it does not exist:

if (!window.location.getParameter ) {
  window.location.getParameter = function(key) {
    function parseParams() {
        var params = {},
            e,
            a = /\+/g,  // Regex for replacing addition symbol with a space
            r = /([^&=]+)=?([^&]*)/g,
            d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
            q = window.location.search.substring(1);

        while (e = r.exec(q))
            params[d(e[1])] = d(e[2]);

        return params;
    }

    if (!this.queryStringParams)
        this.queryStringParams = parseParams(); 

    return this.queryStringParams[key];
  };
}

This function is more or less from Ryan Phelan, but it is wrapped differently: clear name and no dependencies of other javascript libraries. More about this function on my blog.

1 upvote
  flag
Looks like window.location.getParameter() has been removed from Chrome. – mhenry1384
2 upvote
  flag
Yes, it is gone now, but I like this function and its name. – Anatoly Mironov
function getUrlVar(key){
    var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search); 
    return result && unescape(result[1]) || ""; 
}

https://gist.github.com/1771618

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');
1 upvote
  flag
I think you are doing something similar as me, but I think my approach is MUCH simplier //allinonescript.com/a/21152762/985454 – Qwerty
upvote
  flag
Let me introduce you to (drumroll please) window.location.search! – ErikE

If you're doing more URL manipulation than simply parsing the querystring, you may find URI.js helpful. It is a library for manipulating URLs - and comes with all the bells and whistles. (Sorry for self-advertising here)

to convert your querystring into a map:

var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
  "foo": ["bar", "world"],
  "bar": "baz"
}

(URI.js also "fixes" bad querystrings like ?&foo&&bar=baz& to ?foo&bar=baz)

upvote
  flag
// required src/URI.fragmentURI.js to be loaded – JoeB
1 upvote
  flag
+1 URI.js is a great little plugin. You can also do var data = URI.parseQuery('?foo=bar&bar=baz&foo=world'); for same result (docs). – Yarin

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

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

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

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};
upvote
  flag
If your anyway using the jQuery, Then the later method (url_args_replace) can be used via $.param() – adardesign
upvote
  flag
Why do you use document.createElement("a") ? – greg
1 upvote
  flag
@greg to create the element in the browser engine, which will parse a url for you and provide search and href methods for interacting with the url string. – BMitch
http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
  • Regular key/value pair (?param=value)
  • Keys w/o value (?param : no equal sign or value)
  • Keys w/ empty value (?param= : equal sign, but no value to right of equal sign)
  • Repeated Keys (?param=1&param=2)
  • Removes Empty Keys (?&& : no key or value)

Code:

  • var queryString = window.location.search || '';
    var keyValPairs = [];
    var params      = {};
    queryString     = queryString.substr(1);
    
    if (queryString.length)
    {
       keyValPairs = queryString.split('&');
       for (pairNum in keyValPairs)
       {
          var key = keyValPairs[pairNum].split('=')[0];
          if (!key.length) continue;
          if (typeof params[key] === 'undefined')
             params[key] = [];
          params[key].push(keyValPairs[pairNum].split('=')[1]);
       }
    }
    

How to Call:

  • params['key'];  // returns an array of values (1..n)
    

Output:

  • key            ["value"]
    keyemptyvalue  [""]
    keynovalue     [undefined, "nowhasvalue"]
    

This one works fine

function getQuerystring(key) {
    var query = window.location.search.substring(1);
    alert(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

1 upvote
  flag
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. – Rup
upvote
  flag
@Rup you are right...actually in my code it'll always be a number rather than any special characters, so missed ... – IT ppl
upvote
  flag
Think you forgot to remove the alert ;) – gregers

The following function returns an object version of your queryString. You can simply write obj.key1 and obj.key2 to access values of key1 and key2 in parameter.

function getQueryStringObject()
{
    var querystring = document.location.search.replace('?','').split( '&' );
    var objQueryString={};
    var key="",val="";
    if(typeof querystring == 'undefined')
    {
        return (typeof querystring);
    }
    for(i=0;i<querystring.length;i++)
    {
        key=querystring[i].split("=")[0];
        val=querystring[i].split("=")[1];
        objQueryString[key] = val;
    }
    return objQueryString;
}

And to use this function you can write

var obj= getQueryStringObject();
alert(obj.key1);

I like this one (taken from jquery-howto.blogspot.co.uk):

// get an array with all querystring values
// example: var valor = getUrlVars()["valor"];
function getUrlVars() {
    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;
}

Works great for me.

URLSearchParams

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

Safari Nightly has implemented it, and it is in development for Microsoft Edge as well. There is a google-suggested URLSearchParams polyfill for the stable versions of Safari, Edge, and IE.

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

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

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

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

let params = new URL('https://example.com?foo=1&bar=2').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.

26 upvote
  flag
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
upvote
  flag
IE is still missing out... not that I'm using it :( – mlt
4 upvote
  flag
This should be at the top... – Alister Norris
upvote
  flag
Those two downvoters probably missed (like I just did) the fact that you have to use .get instead of just . – Nakilon
7 upvote
  flag
You don't actually need to slice(1) on .search, you can use it directly. URLSearchParams can handle the leading ?. – Jason C
upvote
  flag
Please vote for this bug to get fixed. This will let the Edge team know there is interest! – styfle
upvote
  flag
URLSearchParams is no good because it doesn't return the actual values of a URL's parameters. – Melab
upvote
  flag
This new URL('https://example.com?foo=1&bar=2') is not working for android url file:///android_asset/... – shah

Here is a fast way to get an object similar to the PHP $_GET array:

function get_query(){
    var url = location.search;
    var qs = url.substring(url.indexOf('?') + 1).split('&');
    for(var i = 0, result = {}; i < qs.length; i++){
        qs[i] = qs[i].split('=');
        result[qs[i][0]] = decodeURIComponent(qs[i][1]);
    }
    return result;
}

Usage:

var $_GET = get_query();

For the query string x=5&y&z=hello&x=6 this returns the object:

{
  x: "6",
  y: undefined,
  z: "hello"
}
upvote
  flag
if you need it as a jQuery plugin, here it is: (function($) { $.extend({ get_query: function (name) { var url = location.href; var qs = url.substring(url.indexOf('?') + 1).split('&'); for(var i = 0, result = {}; i < qs.length; i++){ qs[i] = qs[i].split('='); result[qs[i][0]] = qs[i][1]; } return result; } }); })(jQuery); and use like this: $.get_query() – tim
upvote
  flag
Thanks. I also ended up using this. I added this before your return statement: if (param) return result[param], that way i can also do get_query('foo') if needed – sqram
1 upvote
  flag
Not working if you have hashes. For example: test.aspx?test=t1#default. Will return { test: "t1#default" } and I expect {test : "t1" } – Bogdan M.
upvote
  flag
@BogdanM: indeed. location.href would have to be replaced with location.search. – Dan Dascalescu
upvote
  flag
This is my favorite answer here personally. getting an object is ideal because we can handle the object however we want to later. – Amir5000

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.

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 = location.search.split(name + '=')[1];
         return queryStringFromStartOfValue !== undefined ? queryStringFromStartOfValue.split('&')[0] : null;
6 upvote
  flag
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
3 upvote
  flag
However, if you know the parameter name are expecting, This will be the faster approach. – Martin Borthiry
upvote
  flag
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
upvote
  flag
Cool! I made a one-liner: function get(param){return decodeURIComponent((location.search.split(param+'=')[1]||'')‌​.split('&')[0])} – niutech
upvote
  flag
I had to change the second line to return half !== undefined ? decodeURIComponent(half[1].split('&')[0]) : null; to get it to work – divillysausages

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

This function converts the querystring to a JSON-like object, it also handles value-less and multi-value parameters:

"use strict";
function getQuerystringData(name) {
    var data = { };
    var parameters = window.location.search.substring(1).split("&");
    for (var i = 0, j = parameters.length; i < j; i++) {
        var parameter = parameters[i].split("=");
        var parameterName = decodeURIComponent(parameter[0]);
        var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
        var dataType = typeof data[parameterName];
        if (dataType === "undefined") {
            data[parameterName] = parameterValue;
        } else if (dataType === "array") {
            data[parameterName].push(parameterValue);
        } else {
            data[parameterName] = [data[parameterName]];
            data[parameterName].push(parameterValue);
        }
    }
    return typeof name === "string" ? data[name] : data;
}

We perform a check for undefined on parameter[1] because decodeURIComponent returns the string "undefined" if the variable is undefined, and that's wrong.

Usage:

"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");

There is a nice little url utility for this with some cool sugaring:

http://www.example.com/path/index.html?silly=willy#chucky=cheese

url();            // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain');    // example.com
url('1');         // path
url('-1');        // index.html
url('?');         // silly=willy
url('?silly');    // willy
url('?poo');      // (an empty string)
url('#');         // chucky=cheese
url('#chucky');   // cheese
url('#poo');      // (an empty string)

Check out more examples and download here: https://github.com/websanova/js-url#url

One-liner to get the query:

var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
6 upvote
  flag
Triggers error if the key doesn't exist, try this maybe? (location.search.match(new RegExp('kiosk_modeasdf' + "=(.*?)($|\&)", "i")) || [])[1] – Brad Koch
upvote
  flag
@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
1 upvote
  flag
@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
upvote
  flag
i think you forgot testing for key starting with either '?' or '&' like: var result = location.search.match(new RegExp("[\?\&]" + key + "=(.*?)($|\&)", "i")); – e-frank

This the most simple and small function JavaScript to get int ans String parameter value from URL

/* THIS FUNCTION IS TO FETCH INT PARAMETER VALUES */

function getParameterint(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=parseInt(url.replace(param+"=",""));
            alert(n); 
}
getParameteraint("page");
getParameteraint("pagee");

/*THIS FUNCTION IS TO FETCH STRING PARAMETER*/
function getParameterstr(param) {
            var val = document.URL;
            var url = val.substr(val.indexOf(param))  
            var n=url.replace(param+"=","");
            alert(n); 
}
getParameterstr("str");

Source And DEMO : http://bloggerplugnplay.blogspot.in/2012/08/how-to-get-url-parameter-in-javascript.html

1 upvote
  flag
I think that can be easily defeated e.g. ?xyz=page&str=Expected&page=123 won't return 123 because it picks up the page string from xyz=page, and str will return Expected&page=123 rather than just Expected if it's not the last value on the line, etc. You're also not decodeUriComponent-ing the values extracted. Plus I couldn't try your demo - I got redirected to a betting website?? – Rup
upvote
  flag
@Rup you are talking about a RARE/WORST case.. But in normal and regular cases this code works fine and solves the purpose ...And about DEMO its working fine and shows how this function works! Thanks ! – jolly.exe
1 upvote
  flag
OK, finally managed to get your demo through adfly. Yes, that works OK but only because you have just the one string parameter and it's last - try using more than one and switching the orders around. Try putting the pagee parameter before the page parameter and it'll fail. For example here's your demo with the order of the three reversed. The other problem is if someone posts a string with a non-ASCII character in it, e.g. a space - it'll get URI encoded and you're not decoding that afterwards. – Rup

I developed a small library using techniques listed here to create an easy to use, drop-in solution to anyones troubles; It can be found here:

https://github.com/Nijikokun/query-js

Usage

Fetching specific parameter/key:

query.get('param');

Using the builder to fetch the entire object:

var storage = query.build();
console.log(storage.param);

and tons more... check the github link for more examples.

Features

  1. Caching on both decoding and parameters
  2. Supports hash query strings #hello?page=3
  3. Supports passing custom queries
  4. Supports Array / Object Parameters user[]="jim"&user[]="bob"
  5. Supports empty management &&
  6. Supports declaration parameters without values name&hello="world"
  7. Supports repeated parameters param=1&param=2
  8. Clean, compact, and readable source 4kb
  9. AMD, Require, Node support
function GetQueryStringParams(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');

    for (var i = 0; i < sURLVariables.length; i++)
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam)
        {
            return sParameterName[1];
        }
    }
}​

And this is how you can use this function assuming the URL is

http://dummy.com/?stringtext=jquery&stringword=jquerybyexample

var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');
upvote
  flag
There's a few implementations of this approach here already. At the very least you need to decodeUriComponent() the result values. This might also misbehave if you don't specify a value, e.g. ?stringtext&stringword=foo. – Rup

From the MDN:

function loadPageVar (sVar) {
  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}

alert(loadPageVar("name"));
upvote
  flag
Thank you. I needed to catch lat lng values coming back from Controller Action so I could set Google Map javascript yours just went right in and worked. – JustJohn

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'}
4 upvote
  flag
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
upvote
  flag
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
1 upvote
  flag
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
1 upvote
  flag
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
1 upvote
  flag
I would use location.search.substr(1) instead of location.href.split('?')[1] to avoid picking up hash (#anchor) along with the last query parameter. – mlt
upvote
  flag
Yes, let me also introduce you to location.search! – ErikE

I believe this to be an accurate and concise way to achieve this (modified from http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}
upvote
  flag
That looks reasonable! You probably need to decode the values taken from the query string in case they've been encoded for submission with %s or +s though. – Rup
upvote
  flag
Good call — a simple modification. – Gabriel Ryan Nahmias

A very lightweight jQuery method:

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

And to alert, for example ?q

alert(request.q)
1 upvote
  flag
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
upvote
  flag
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
upvote
  flag
doesn't work for ?foo=1&foo=2, though... – mtness
1 upvote
  flag
@mtness you're right, it didn't. I just updated so now it does :) thanks – Roi

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'
}

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;
};
1 upvote
  flag
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
2 upvote
  flag
Yes, I know. But in my app i integrate 3rd party js navigation, which have some parameters after hash sign. – Ph0en1x
upvote
  flag
For example, in the Google search page, the searching query is followed by the hash sign '#'. – etlds

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:pass@example.com: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);
upvote
  flag
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
upvote
  flag
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

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

var url = require('url');

url.parse('http://example.com/?bob=123', true).query;

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

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

3 upvote
  flag
As the question mentions jQuery, I would assume this is in the browser. – Luca Spiller
1 upvote
  flag
@LucaSpiller A lot of people use Node.js modules in the browser using Browserify, so this would be relevant to a lot of people. – andrezsanchez
upvote
  flag
The documentation for the url module's API is here: nodejs.org/api/url.html – andrezsanchez
upvote
  flag
@AndreZS I've updated the answer to explicitly mention Browserify as you are correct that it could be used via that. The original only mentioned Node.js, hence my comment. – Luca Spiller
upvote
  flag
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. – Andrew Grothe

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

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>
upvote
  flag
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
upvote
  flag
... although it's the same as Andy E's solution above. – Rup
upvote
  flag
The link is broken. – Peter Mortensen

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;
}
upvote
  flag
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
upvote
  flag
Dar Lessons has now released 1.1 which fixes the script injection attack. – Rup

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.

upvote
  flag
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
2 upvote
  flag

There's a robust implementation in Node.js's source
https://github.com/joyent/node/blob/master/lib/querystring.js

Also TJ's qs does nested params parsing
https://github.com/visionmedia/node-querystring

var getUrlParameters = function (name, url) {
    if (!name) {
        return undefined;
    }

    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    url = url || location.search;

    var regex = new RegExp('[\\?&#]' + name + '=?([^&#]*)', 'gi'), result, resultList = [];

    while (result = regex.exec(url)) {
        resultList.push(decodeURIComponent(result[1].replace(/\+/g, ' ')));
    }

    return resultList.length ? resultList.length === 1 ? resultList[0] : resultList : undefined;
};
upvote
  flag
this is a lot better than accepted solution to handle array values in query string. i.e. arr[]=1&arr[]=2 – allenhwkim

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
upvote
  flag
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
upvote
  flag
but what if you have example.com/3 (MVC routing) – JoshYates1980

There are many solutions to retrieve URI query values, I prefer this one because it's short and works great:

function get(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}
upvote
  flag
That's neat, although that's essentially the top accepted answer distilled down a bit, e.g. you've lost the decoding of pluses-for-spaces in values . The encodeURIComponent for the key name is new, though, and on one hand more correct than the accepted answer for considering encodings in the key but on the other will still miss non-minimal encodings, e.g. get("key") won't match ?k%65y=value. – Rup

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

We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:

var name = Arg.get("name");

or getting the whole lot:

var params = Arg.all();

and if you care about the difference between ?query=true and #hash=true then you can use the Arg.query() and Arg.hash() methods.

upvote
  flag
you saved me man.. arg.js is the solution none of the solutions is getting the values from # in IE 8..:( any one searching for IE8 # get from request this is the solution.. – Dilip Rajkumar

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('='); }));
upvote
  flag
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
upvote
  flag
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
1 upvote
  flag
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

tl;dr

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

var qd = {};
if (location.search) 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   (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
Multi-lined:
var qd = {};
if (location.search) location.search.substr(1).split("&").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

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"



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"]



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 (location.search == ""), the result is somewhat misleading qd == {"": undefined}. It is suggested to check the querystring before launching the parsing function likeso:

if (location.search) location.search.substr(1).split("&").forEach(...)
1 upvote
  flag
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
2 upvote
  flag
@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
upvote
  flag
@twig will not work in IE8 – sqram
upvote
  flag
@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 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Qwerty
upvote
  flag
@katsh also it's not problem to rewrite it to normal for loop, but the solution wouldn't be this elegant :) – Qwerty
1 upvote
  flag
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
upvote
  flag
Just curious, why the trailing comma when creating the array of one element? CC @Casey. – Dan Dascalescu
upvote
  flag
@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. – Qwerty
1 upvote
  flag
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
upvote
  flag
@loop Thank you! fixed using v = v && decodeURIComponent(v) – Qwerty
upvote
  flag
@Querty, wouldn't that be v = s && decodeURIComponent(v) ? Your version will never execute decodeURIComponent. – Isochronous
upvote
  flag
@Querty, whoops, I meant v = k && decodeURIComponent(v). – Isochronous
upvote
  flag
@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
upvote
  flag
@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. – Qwerty
upvote
  flag
Why is this not decoding the 'name' of the value as well? It may very well have encoded characters. – Triynko
upvote
  flag
@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(). – Qwerty
upvote
  flag
@ErikE what was your expected result? – Qwerty
upvote
  flag
I'm sure that if you're interested you can come up with something sensible. My comment was as much for any readers as for you. – ErikE
upvote
  flag
@ErikE I am sorry that you feel offended by my question. – Qwerty
upvote
  flag
@ErikE The value component must be encoded according to specification. Therefore your querystring is invalid. If you had used any querystring builder, you would've received a valid querystring like ?main=b%3D5&alternate=b%3D6 Try it yourself var usp = new URLSearchParams(); usp.append('main', 'b=5'); usp.toString() – Qwerty
upvote
  flag
I'm not offended at all and didn't mean my answer to be stiff or defensive in any way. I simply said what I meant to say already. Thanks for your time! – ErikE
upvote
  flag
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 location.search is non-empty before running your code, so the dictionary is empty if there are no params. – Brian S

Doing this reliably is more involved than one may think at first.

  1. location.search, which is used in other answers, is brittle and should be avoided - for example, it returns empty if someone screws up and puts a #fragment identifier before the ?query string.
  2. There are a number of ways URLs get automatically escaped in the browser, which makes decodeURIComponent pretty much mandatory, in my opinion.
  3. Many query strings are generated from user input, which means assumptions about the URL content are very bad. Including very basic things like that each key is unique or even has a value.

To solve this, here is a configurable API with a healthy dose of defensive programming. Note that it can be made half the size if you are willing to hardcode some of the variables, or if the input can never include hasOwnProperty, etc.

Version 1: Returns a data object with names and values for each parameter. It effectively de-duplicates them and always respects the first one found from left-to-right.

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

    var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

    if (!url || typeof url !== 'string') {
        url = location.href; // more robust than location.search, which is flaky
    }
    if (!paramKey || typeof paramKey !== 'string') {
        paramKey = '&';
    }
    if (!pairKey || typeof pairKey !== 'string') {
        pairKey = '=';
    }
    // when you do not explicitly tell the API...
    if (arguments.length < 5) {
        // it will unescape parameter keys and values by default...
        decode = true;
    }

    queryStart = url.indexOf('?');
    if (queryStart >= 0) {
        // grab everything after the very first ? question mark...
        query = url.substring(queryStart + 1);
    } else {
        // assume the input is already parameter data...
        query = url;
    }
    // remove fragment identifiers...
    fragStart = query.indexOf('#');
    if (fragStart >= 0) {
        // remove everything after the first # hash mark...
        query = query.substring(0, fragStart);
    }
    // make sure at this point we have enough material to do something useful...
    if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
        // we no longer need the whole query, so get the parameters...
        query = query.split(paramKey);
        result = {};
        // loop through the parameters...
        for (i = 0, len = query.length; i < len; i = i + 1) {
            pairKeyStart = query[i].indexOf(pairKey);
            if (pairKeyStart >= 0) {
                name = query[i].substring(0, pairKeyStart);
            } else {
                name = query[i];
            }
            // only continue for non-empty names that we have not seen before...
            if (name && !Object.prototype.hasOwnProperty.call(result, name)) {
                if (decode) {
                    // unescape characters with special meaning like ? and #
                    name = decodeURIComponent(name);
                }
                if (pairKeyStart >= 0) {
                    value = query[i].substring(pairKeyStart + 1);
                    if (value) {
                        if (decode) {
                            value = decodeURIComponent(value);
                        }
                    } else {
                        value = missingValue;
                    }
                } else {
                    value = missingValue;
                }
                result[name] = value;
            }
        }
        return result;
    }
}

Version 2: Returns a data map object with two identical length arrays, one for names and one for values, with an index for each parameter. This one supports duplicate names and intentionally does not de-duplicate them, because that is probably why you would want to use this format.

function getQueryData(url, paramKey, pairKey, missingValue, decode) {

   var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;

   if (!url || typeof url !== 'string') {
       url = location.href; // more robust than location.search, which is flaky
   }
   if (!paramKey || typeof paramKey !== 'string') {
       paramKey = '&';
   }
   if (!pairKey || typeof pairKey !== 'string') {
       pairKey = '=';
   }
   // when you do not explicitly tell the API...
   if (arguments.length < 5) {
       // it will unescape parameter keys and values by default...
       decode = true;
   }

   queryStart = url.indexOf('?');
   if (queryStart >= 0) {
       // grab everything after the very first ? question mark...
       query = url.substring(queryStart + 1);
   } else {
       // assume the input is already parameter data...
       query = url;
   }
   // remove fragment identifiers...
   fragStart = query.indexOf('#');
   if (fragStart >= 0) {
       // remove everything after the first # hash mark...
       query = query.substring(0, fragStart);
   }
   // make sure at this point we have enough material to do something useful...
   if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
       // we no longer need the whole query, so get the parameters...
       query = query.split(paramKey);
       result = {
           names: [],
           values: []
       };
       // loop through the parameters...
       for (i = 0, len = query.length; i < len; i = i + 1) {
           pairKeyStart = query[i].indexOf(pairKey);
           if (pairKeyStart >= 0) {
               name = query[i].substring(0, pairKeyStart);
           } else {
               name = query[i];
           }
           // only continue for non-empty names...
           if (name) {
               if (decode) {
                   // unescape characters with special meaning like ? and #
                   name = decodeURIComponent(name);
               }
               if (pairKeyStart >= 0) {
                   value = query[i].substring(pairKeyStart + 1);
                   if (value) {
                       if (decode) {
                           value = decodeURIComponent(value);
                       }
                   } else {
                       value = missingValue;
                   }
               } else {
                   value = missingValue;
               }
               result.names.push(name);
               result.values.push(value);
           }
       }
       return result;
   }

}

2 upvote
  flag
Neat, though the majority of answers here deal with splitting up the query part into parameters rather than extracting it from an arbitrary URL. Most of them assume we're on the current page and so just use location.search to get the string you're extracting. – Rup
upvote
  flag
this is not the point of the question, we need to extract each pair of query parameters as key/value, supporting arrays, empty values, etc.. by the way, "?hello#haha" is not a good behavior, as the #haha usually refeers to an anchor which does not make part of the parameter "hello" – Donatello
1 upvote
  flag
I took the very short and vague question to mean something very different than what everyone else did. It's now obvious to me what was meant, and I have updated my answer to include a significantly better design that is on par. – Seth Holladay

This will parse variables AND arrays from a URL string. It uses neither regex or any external library.

function url2json(url) {
   var obj={};
   function arr_vals(arr){
      if (arr.indexOf(',') > 1){
         var vals = arr.slice(1, -1).split(',');
         var arr = [];
         for (var i = 0; i < vals.length; i++)
            arr[i]=vals[i];
         return arr;
      }
      else
         return arr.slice(1, -1);
   }
   function eval_var(avar){
      if (!avar[1])
          obj[avar[0]] = '';
      else
      if (avar[1].indexOf('[') == 0)
         obj[avar[0]] = arr_vals(avar[1]);
      else
         obj[avar[0]] = avar[1];
   }
   if (url.indexOf('?') > -1){
      var params = url.split('?')[1];
      if(params.indexOf('&') > 2){
         var vars = params.split('&');
         for (var i in vars)
            eval_var(vars[i].split('='));
      }
      else
         eval_var(params.split('='));
   }
   return obj;
}

Example:

var url = "http://www.x.com?luckyNums=[31,21,6]&name=John&favFoods=[pizza]&noVal"
console.log(url2json(url));

Output:

[object]
   noVal: ""
   favFoods: "pizza"
   name:     "John"
   luckyNums:
      0: "31"
      1: "21"
      2: "6"

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

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

Get all querystring parameters including checkbox values (arrays).

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

So I wrote this function:

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

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

Support:

  1. Empty values (key= / key)
  2. Key value (key=value)
  3. Arrays (key[]=value)
  4. Hash (the hash tag is split out)

Notes:

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

If the space is + it remains a +.

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

Usage:

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

Return:

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

Demo:

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

Info

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

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

upvote
  flag
Very neat, though I find it hard to believe that writing it pre-minified actually helps anything but the first parse, or helps in general if people are going to minify their production code anyway. Most of the functions here don't need to strip the hash-part because they start with location.search which doesn't contain it. I'm also not clear what you mean "bitwise operators" - you're using empty-or-undefined-is-false in a couple of places which is as close as you get but there's no bit manipulation here. – Rup
upvote
  flag
upvote
  flag
If you use arrays for more than checkbox values, add: if ( v.charAt(0) == '[' ) { v = v.replace('[', '["').replace(']', '"]').replace(',', '","'); v = JSON && JSON.parse(v) || $.parseJSON(v); } before "c[k]?typeof ..." – Alex Man

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

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;
  }
};
upvote
  flag
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
upvote
  flag
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

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

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

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

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

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"];
upvote
  flag
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
upvote
  flag
@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

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

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

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

upvote
  flag
That's basically the same as the top answer though, less some some of the unescaping, just put on the String.prototype. – Rup
upvote
  flag
@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

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

It will handle the following querystring...

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

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

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

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

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

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

The code:

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


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

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

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

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

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

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

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

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

    //# Return the r(eturn value)
    return r;
};
upvote
  flag
That's neat, although I disagree the ?key=1&key[]=2&key[]=3 case is a bug: I'd say malformed input, even if .NET will process it. I also disagree with using ; as a separator - where's the spec for that? - although a lot of people do want support for it (?). You're returning a fake array too, even when there are no user-specified keys, although if consumers treat it as read-only that ought not matter. Why check the indexOf result as a string? And where's the double-decode in Andy E's answer? – Rup
upvote
  flag
Malformed: I'm not certain if .NET processes it or not, but I've never seen the [] notation in a QS. But I did mention this was controversial ;) Also, if we can process it, then why not!? Fake Array: as per Andy E's example. indexOf: As per Andy E's example. Semi-Colan: It was mentioned in Andy E's/Wikipedia, but I've also never seen that (and a comment is there that tells you how to remove the feature). Re-Decode: jsbin.com/adali3/2/edit, pN is d()'d at assignment, then again and again below. – Campbeln
upvote
  flag
Oops, my mistake: I was looking at Andy's code in the answer not the linked version. – Rup
upvote
  flag
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]; } } – Mike Clark
1 upvote
  flag
I've been using this for a while now, and it's been great so far. Except for handling urlencoded arrays. Using q = decodeURIComponent(window.location.search.substring(1)), helps it do that too. – Vladislav Dimitrov

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:////allinonescript.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.

upvote
  flag
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
upvote
  flag
Parameter names should never need decoding. – Vladimir Kornea
1 upvote
  flag
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
upvote
  flag
It's never good practice. – Vladimir Kornea
upvote
  flag
The solution is good, but why no semicolon at the end of statements? – Sudar
upvote
  flag
@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. – Vladimir Kornea
7 upvote
  flag
'Amazing how many overly complicated and incomplete solutions are posted here' Lol, the irony.. – NiCk Newman

Most pretty but basic:

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

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

upvote
  flag
Neat! You may need to trim the leading '?' off the first item (I don't know if that's always necessary, but many answers here do) and you need to perform some unescaping of the value too (decodeURIComponent, plusses-to-spaces) – Rup
upvote
  flag
Thank you, absolutely, and we also need a .filter(Boolean) to remove an empty string item in list when location.search is empty. That is: location.search.substr(1).split('&').filter(Boolean).map(... – Damien
upvote
  flag
And the reverse: a query string from the returned hashmap: $.map(queryhash, function(v,k){ return [k,v].join('=')}).join('&') – Damien
// Parse query string
var params = {}, queryString = location.hash.substring(1),
    regex = /([^&=]+)=([^&]*)/g,
    m;
while (m = regex.exec(queryString)) {
    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
upvote
  flag
Uh, hash != querystring. – hackel

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

Here's a jsfiddle example.

[
  '?a=a',
  '&b=a',
  '&b=b',
  '&c[]=a',
  '&c[]=b',
  '&d[a]=a',
  '&d[a]=x',
  '&e[a][]=a',
  '&e[a][]=b',
  '&f[a][b]=a',
  '&f[a][b]=x',
  '&g[a][b][]=a',
  '&g[a][b][]=b',
  '&h=%2B+%25',
  '&i[aa=b',
  '&i[]=b',
  '&j=',
  '&k',
  '&=l',
  '&abc=foo',
  '&def=%5Basf%5D',
  '&ghi=[j%3Dkl]',
  '&xy%3Dz=5',
  '&foo=b%3Dar',
  '&xy%5Bz=5'
].join('');

Given any of the above test examples.

var qs = function(a) {
  var b, c, e;
  b = {};
  c = function(d) {
    return d && decodeURIComponent(d.replace(/\+/g, " "));
  };
  e = function(f, g, h) {
    var i, j, k, l;
    h = h ? h : null;
    i = /(.+?)\[(.+?)?\](.+)?/g.exec(g);
    if (i) {
      [j, k, l] = [i[1], i[2], i[3]]
      if (k === void 0) {
        if (f[j] === void 0) {
          f[j] = [];
        }
        f[j].push(h);
      } else {
        if (typeof f[j] !== "object") {
          f[j] = {};
        }
        if (l) {
          e(f[j], k + l, h);
        } else {
          e(f[j], k, h);
        }
      }
    } else {
      if (f.hasOwnProperty(g)) {
        if (Array.isArray(f[g])) {
          f[g].push(h);
        } else {
          f[g] = [].concat.apply([f[g]], [h]);
        }
      } else {
        f[g] = h;
      }
      return f[g];
    }
  };
  a.replace(/^(\?|#)/, "").replace(/([^#&=?]+)?=?([^&=]+)?/g, function(m, n, o) {
    n && e(b, c(n), c(o));
  });
  return b;
};
3 upvote
  flag
Looks broadly good, but why pre-minify it? It's tricky to follow in places as-is; in particular you're doing a few nasty things around the right-square-bracket line. Also an input something like c[xx=a&c[]=b will crash it. – Rup
upvote
  flag
My intention wasn't to pre-minify it, rather I just suck at naming variables, so I didn't try to come up with better names. I reworked the code to accommodate your example inputs and respond appropriately. I also switched to using regex's instead of trying to slice strings (which as you pointed out didn't always work). – Peter T Bosse II

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