Skip to content

Instantly share code, notes, and snippets.

@NTICompass
Last active March 3, 2016 17:07
Show Gist options
  • Select an option

  • Save NTICompass/3528917 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown
Author

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

@NTICompass

Copy link
Copy Markdown
Author

Removed jQuery dependency.

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