JSFiddle - React, Tailwind, and code Playground
HTML
<p>This JavaScript function can parse any query string with arbitrarily nested arrays or objects.</p>
JavaScript
var a = "?a=a&b=a&b=b&c[]=a&c[]=b&d[a]=a&d[a]=x&e[a][]=a&e[a][]=b&f[a][b]=a&f[a][b]=x&g[a][b][]=a&g[a][b][]=b&h=%2B+%25&i[aa=b&i[]=b&j=&k&=l&abc=foo&def=%5Basf%5D&ghi=[j%3Dkl]&xy%3Dz=5&foo=b%3Dar&xy%5Bz=5"
qs = function(a) {
var b, c, e;
b = {};
c = function(d) {
return d && decodeURIComponent(d.replace(/\+/g, " "));
};
e = function(f, g, h) {
var i, j, k, l;
h = h ? h : null;
i = /(.+?)\[(.+?)?\](.+)?/g.exec(g);
if (i) {
[j, k, l] = [i[1], i[2], i[3]]
if (k === void 0) {
if (f[j] === void 0) {
f[j] = [];
}
f[j].push(h);
} else {
if (typeof f[j] !== "object") {
f[j] = {};
}
if (l) {
e(f[j], k + l, h);
} else {
e(f[j], k, h);
}
}
} else {
if (f.hasOwnProperty(g)) {
if (Array.isArray(f[g])) {
f[g].push(h);
} else {
f[g] = [].concat.apply([f[g]], [h]);
}
} else {
f[g] = h;
}
return f[g];
}
};
a.replace(/^(\?|#)/, "").replace(/([^#&=?]+)?=?([^&=]+)?/g, function(m, n, o) {
n && e(b, c(n), c(o));
});
return b;
};
// document.body.appendChild(document.createElement('pre')).textContent = a.replace(/\&/g, "\n\&");
document.body.appendChild(document.createElement('pre')).textContent = JSON.stringify(qs(a), null, ' ');