Skip to content

Instantly share code, notes, and snippets.

@NTICompass
Last active March 3, 2016 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NTICompass/3528917 to your computer and use it in GitHub Desktop.
Save NTICompass/3528917 to your computer and use it in GitHub Desktop.
Parse GET query string in JavaScript
function parseQuery(str){
var ret = {};
str.split("&").forEach(function(value){
var data = value.split('='),
name = decodeURIComponent(data.shift()),
val = decodeURIComponent(data.join("=")).replace('+', ' '),
nameVal = name.match(/(.*)\[(.*)\]/);
if(nameVal === null){
ret[name] = val;
}
else{
name = nameVal[1];
nameVal = nameVal[2];
if(nameVal === ''){
if(ret[name] && Array.isArray(ret[name])){
ret[name].push(val);
}
else{
ret[name] = [val];
}
}
else{
if(!ret[name]){
ret[name] = {};
}
ret[name][nameVal] = val;
}
}
});
return ret;
}
@NTICompass
Copy link
Author

Note: This doesn't support query strings like param2[key1]=value1&param2[key2]=value2, it currently only supports param2[]=value1&param2[]=value2.

@NTICompass
Copy link
Author

Updated to support param2[key1]=value1&param2[key2]=value2 :-)

@NTICompass
Copy link
Author

Removed jQuery dependency.

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