Last active
August 20, 2020 14:18
-
-
Save hitGovernor/7f2ed0e75a6f03eb0780177d91a9c1cb to your computer and use it in GitHub Desktop.
turns query params into key:value pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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