Skip to content

Instantly share code, notes, and snippets.

@n8jadams
Created April 30, 2022 01:53
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 n8jadams/76c04dd487b070b15d47e16e808bfdca to your computer and use it in GitHub Desktop.
Save n8jadams/76c04dd487b070b15d47e16e808bfdca to your computer and use it in GitHub Desktop.
Parse query string. (Just use URLSearchParams instead of this)
function parseQueryString(query) {
query = query.substring(query.indexOf('?') + 1);
let re = /([^&=]+)=?([^&]*)/g;
let decodeRE = /\+/g;
let decode = function(str) {
return decodeURIComponent(str.replace(decodeRE, ' '));
};
let params = {},
e;
while ((e = re.exec(query))) {
let k = decode(e[1]),
v = decode(e[2]);
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
} else params[k] = v;
}
let assign = function(obj, keyPath, value) {
let lastKeyIndex = keyPath.length - 1;
for (let i = 0; i < lastKeyIndex; ++i) {
let key = keyPath[i];
if (!(key in obj)) obj[key] = {};
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
};
for (let prop in params) {
let structure = prop.split('[');
if (structure.length > 1) {
let levels = [];
structure.forEach(function(item, i) {
let key = item.replace(/[?[\]\\ ]/g, '');
levels.push(key);
});
assign(params, levels, params[prop]);
delete params[prop];
}
}
return params;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment