Last active
March 3, 2016 17:07
-
-
Save NTICompass/3528917 to your computer and use it in GitHub Desktop.
Parse GET query string in JavaScript
This file contains hidden or 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 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; | |
} |
Updated to support param2[key1]=value1¶m2[key2]=value2
:-)
Removed jQuery dependency.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This doesn't support query strings like
param2[key1]=value1¶m2[key2]=value2
, it currently only supportsparam2[]=value1¶m2[]=value2
.