Created
May 3, 2012 20:11
-
-
Save robcolburn/2588921 to your computer and use it in GitHub Desktop.
Parse query string parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getQuery(s) { | |
var query = {}, i = s.indexOf('?'); | |
if (i != -1) { | |
s.substr(i+1).replace(/\+/g, ' ').replace(/([^&;=]+)=?([^&;]*)/g, function (m, k, v) { | |
query[decodeURIComponent(k)] = decodeURIComponent(v); | |
}); | |
} | |
return query; | |
} | |
//_GET = getQuery(location.href); |
Thanks! Nice to know people can use this bits I post.
I know where you're coming from, there are often good cases for wanting to pass lists over a query string. I like to think of query-strings as simple key-value maps, so only 1 value per key.
PHP's $_GET
and jQuery's $.param
also allow an alternative bracket-like syntax to be used for array's, as in ?a[]=1&b=2&a[]=3
. I could see supporting that, as it still allows the key-value relationship.
IMO, I like the functions simplicity and map relationship.
If you're looking for something more robust, I recommend @cowboy's:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for posting this snippet, one thing I notice is that it doesn't handle a case where the query string looks like: ?a=1&b=2&a=3, as it overwrites a=1 with a=3 so I modified it slightly to accommodate.
Replaced
With