Skip to content

Instantly share code, notes, and snippets.

@besrabasant
Last active May 7, 2020 15:02
Show Gist options
  • Save besrabasant/88d75dc022595ce37076bff602736d6c to your computer and use it in GitHub Desktop.
Save besrabasant/88d75dc022595ce37076bff602736d6c to your computer and use it in GitHub Desktop.
Get Query String Parameters as JSON Object with JavaScript
function getUrlParameter(name, defaultValue = "") {
query = query.substring(location.search.indexOf("?") + 1);
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g;
var decode = function(str) {
return decodeURIComponent(str.replace(decodeRE, " "));
};
var params = {},
e;
while ((e = re.exec(query))) {
var 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;
}
var assign = function(obj, keyPath, value) {
var lastKeyIndex = keyPath.length - 1;
for (var i = 0; i < lastKeyIndex; ++i) {
var key = keyPath[i];
if (!(key in obj)) obj[key] = {};
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
};
for (var prop in params) {
var structure = prop.split("[");
if (structure.length > 1) {
var levels = [];
structure.forEach(function(item, i) {
var key = item.replace(/[?[\]\\ ]/g, "");
levels.push(key);
});
assign(params, levels, params[prop]);
delete params[prop];
}
}
return params.hasOwnProperty(name) ? params[name] : defaultValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment