Skip to content

Instantly share code, notes, and snippets.

@hitGovernor
Last active August 20, 2020 14:18
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 hitGovernor/7f2ed0e75a6f03eb0780177d91a9c1cb to your computer and use it in GitHub Desktop.
Save hitGovernor/7f2ed0e75a6f03eb0780177d91a9c1cb to your computer and use it in GitHub Desktop.
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