Skip to content

Instantly share code, notes, and snippets.

@rafaelrinaldi
Last active September 25, 2015 06:17
Show Gist options
  • Save rafaelrinaldi/876048 to your computer and use it in GitHub Desktop.
Save rafaelrinaldi/876048 to your computer and use it in GitHub Desktop.
JavaScript query string decoder.
/**
* Simple query string decoder.
*/
var QueryStringDecoder = (function() {
return {
decode: function(url) {
var decoded = {},
count = 0,
pairs = url.slice(url.indexOf('?') + 1).split("&"),
pair;
for(; count < pairs.length; count++) {
pair = pairs[count].split("=");
// Missing "=" returns "null": http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
decoded[pair[0]] = pair[1] || null;
}
return decoded;
}};
})();
@sindresorhus
Copy link

This doesn't handle when a query string doesn't have a value, it should then return null.

See: https://github.com/sindresorhus/query-string

@rafaelrinaldi
Copy link
Author

@sindresorhus Good catch Sindre! Your solution is great, thanks for sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment