Nicholas Ortenzio wrote this little plugin:
jQuery.extend({
getQueryParameters : function(str) {
return (str || document.location.search).replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
}
});
So if the URL is:
http://codepen.io/chriscoyier/pen/uszCr?lunch=sandwich&dinner=stirfry
You can do:
var queryParams = $.getQueryParameters();
And queryParams
will be an object like:
{
"lunch": "sandwich",
"dinner": "stirfry"
}
So very handy. Wondering if there’s a way to also provide downloadable snippets like this for easy importing into Codebox, etc.
I cringe every time I see custom query string parsing algorithms because they’re pretty much always wrong.
For example,
?foo=bar;foo=baz
should produce:And that code obviously can’t.
zzzzBov, what about this as a modified alternative?
@Ben
This is the sort of feature where you should set up unit tests before writing. With a little bit of testing, I found that the following strings failed:
'?=&='
'?foo=bar&foo=baz;foo=qux'
''
** I modified the algorithm to remove
|| document.location.search
to test strings explicitly@zzzzBav: If you pass that query string to PHP (assuming you’ve defined “;” as a param separator), it would produce the same as this script: last value wins the key. To produce the array you suggest, you’d need this:
?foo[]=bar;foo[]=baz
. The script above would still only produce{"foo[]":"baz"}
.It’s a narrow scope script not intended for advanced data structures. Taken in that context, it’s elegant, fast, and easy to implement.
Sorry, meant zzzzBov. :)
@Joe t, PHP uses a completely different query string parsing standard. Use caution when parsing query strings that are used in PHP applications.
@zzzzBov, By that logic we should beware of query strings used by any language, as there is no broadly accepted standard. Ruby, PHP, Python, .Net… Who’s right? Which one should JavaScript follow? (And why is
query
part of the JavaScriptlocation
object yet there’s no built-in parser?)Granted, expecting a JavaScript query string parser to handle all variations out there is ludicrous. Due caution should always be exercised.
It’s an example of how it can be done, not a universal solution. Since in most cases the programmer who uses it will also control the query string itself, it obviously should be adapted to need. :-)
@zzzzBov I have to agree with @joe. I think the intended use case here would be “normal” query string use. What would be the use cases for the exceptions you found? I see the validity of your initial issue, in that checkboxes and multi-selects would render a query string with redundant keys, but special characters or equal signs without keys? I am interested to hear the situations you have encountered where these are useful cases.
Also unit testing a proposed alternate script in a blog comment feed might be a bit excessive, no?
The whole reason I brought it up is to make people aware that query string parsing is not something that should be left to a crummy home-brewed solution. Edge cases aren’t an issue until you’re bitten by them.
This also doesn’t handle URL encoding. If a URL encoded query string is ran through this, the resulting object will still have the encoded text. Which in my experience is incorrect.
I think there should also be a minor update to the RegEx in the replace to:
This removes all text before the ? The original RegEx requires you to pass in
The update allows you to pass in
jQuery now has
$.getParams(url);
Where do you found this information? Can you pass some link to documentation?
Give this a try, seems to work with the test cases zzzBov mentioned. http://jsfiddle.net/EldonMcGuinness/cb57dusv/
Just wanted to add that I posted this code on my site as a JQuery plugin and use it in my search engine, feel free to try it out.
Should probably handle the no params case better. Modified version. Return {} incase of no/inconsistent str.
Query string parameters should be decoded. So here is fixed example:
What I have done is decorated
n[1]
withdecodeURIComponent
I used this for my site today and made a small improvement to the method. Instead of using ‘map’ array function, I used ‘reduce’ function it returns a single object instead of an array.
Code example:
example_length=10&id=LAF-000021&id=LAF-000028 , I want to covet this json . but it
id is only coming as array.
Works great! However, JSHint doesn’t like this. It complains that there is an “Unexpected use of a comma operator.”