Skip to content

Instantly share code, notes, and snippets.

@krmgns
Created December 25, 2014 20:12
Show Gist options
  • Save krmgns/92b54ad32b24569e7253 to your computer and use it in GitHub Desktop.
Save krmgns/92b54ad32b24569e7253 to your computer and use it in GitHub Desktop.
// Handles also array params well
function parseQueryString(query) {
var pars = (query != null ? query : "").replace(/&+/g, "&").split('&'),
par, key, val, re = /^([\w]+)\[(.*)\]/i, ra, ks, ki, i = 0,
params = {};
while ((par = pars.shift()) && (par = par.split('=', 2))) {
key = decodeURIComponent(par[0]);
// prevent param value going to be "undefined" as string
val = decodeURIComponent(par[1] || "").replace(/\+/g, " ");
// check array params
if (ra = re.exec(key)) {
ks = ra[1];
// init array param
if (!(ks in params)) {
params[ks] = {};
}
// set int key
ki = (ra[2] != "") ? ra[2] : i++;
// set array param
params[ks][ki] = val;
// go on..
continue;
}
// set param
params[key] = val;
}
return params;
}
var query = 'foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last';
var params = parseQueryString(query);
console.log(params)
console.log(params.foo) // 1
console.log(params.bar) // The bar!
console.log(params.arr[0]) // a0
console.log(params.arr[1]) // a1
console.log(params.arr.s) // as
console.log(params.arr.none) // undefined
console.log("isset" in params) // true like: isset($_GET['isset'])
/*
// in php
parse_str('foo=1&bar=The+bar!%20&arr[]=a0&arr[]=a1&arr[s]=as&isset&arr[]=last', $query);
print_r($query);
Array
(
[foo] => 1
[bar] => The bar!
[arr] => Array
(
[0] => a0
[1] => a1
[s] => as
[2] => last
)
[isset] =>
)*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment