Last active
October 21, 2021 12:21
-
-
Save sudosoul/dcdcd7825c3dc0edc3099be9a4c44b2f to your computer and use it in GitHub Desktop.
JavaScript - Get URL QueryString Parameters - ES5 / Best Browser Compatibility
This file contains hidden or 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
/** | |
* Accepts either a URL or querystring and returns an object associating | |
* each querystring parameter to its value. | |
* | |
* Returns an empty object if no querystring parameters found. | |
*/ | |
function getUrlParams(urlOrQueryString) { | |
if ((i = urlOrQueryString.indexOf('?')) >= 0) { | |
const queryString = urlOrQueryString.substring(i+1); | |
if (queryString) { | |
return _mapUrlParams(queryString); | |
} | |
} | |
return {}; | |
} | |
/** | |
* Helper function for `getUrlParams()` | |
* Builds the querystring parameter to value object map. | |
* | |
* @param queryString {string} - The full querystring, without the leading '?'. | |
*/ | |
function _mapUrlParams(queryString) { | |
return queryString | |
.split('&') | |
.reduce(function(urlParams, urlParam) { | |
urlParam = urlParam.split('='); | |
if (Number.isInteger(parseInt(urlParam[1])) && parseInt(urlParam[1]) == urlParam[1]) { | |
urlParams[urlParam[0]] = parseInt(urlParam[1]); | |
} else { | |
urlParams[urlParam[0]] = decodeURI(urlParam[1]); | |
} | |
return urlParams; | |
}, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
function _mapUrlParams(queryString) {
return queryString
.split('&')
.reduce((urlParams, urlParam) => {
urlParam = urlParam.split('=');
const test = Number.isInteger(parseInt(urlParam[1])) && parseInt(urlParam[1]) == urlParam[1];
urlParams[urlParam[0]] = test ? 'parseInt' : 'decodeURI'
return urlParams;
}, {});
}