Skip to content

Instantly share code, notes, and snippets.

@hitGovernor
Last active Aug 20, 2020
Embed
What would you like to do?
turns query params into key:value pairs
/**
* returns an object with all query parameters as key/value pairs
* @param payload - if ommitted, returns all params as an object; if passed as string specifying a parameter,
* returns the value of the specified parameter name; can be passed as object { search: document.location.search, returnKey: {{parameter-name}} }
* @returns {object} - example: http://example.com?a=a-value&B=B-VALUE = > { "a": "a-value", "b": "B-VALUE"}
*/
function getParams(payload) {
var searchString = document.location.search,
returnKey = "";
if (typeof (payload) === "string") {
returnKey = payload;
} else {
payload = payload || {};
searchString = payload.search || searchString;
returnKey = payload.returnKey || returnKey;
}
if (searchString) {
searchString = searchString;
searchString = /\?/.test(searchString) ? searchString.split('?')[1] : searchString;
searchString = searchString.split("&");
if (searchString.length > 0) {
var output = {};
for (var i = 0, max = searchString.length; i < max; i++) {
var tmp = searchString[i].split("=");
output[tmp[0].toLowerCase()] = decodeURIComponent(tmp[1]);
}
return (returnKey) ? output[returnKey] : output;
}
} else {
return (returnKey) ? "" : {};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment