Skip to content

Instantly share code, notes, and snippets.

@sudosoul
Last active February 28, 2019 02:50
Show Gist options
  • Save sudosoul/b9c0b297b437a7c2ede47c3a21c1700b to your computer and use it in GitHub Desktop.
Save sudosoul/b9c0b297b437a7c2ede47c3a21c1700b to your computer and use it in GitHub Desktop.
JavaScript -  Get URL QueryString Parameters - ES6 Features
/**
* 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((urlParams, urlParam) => {
const [key, value] = urlParam.split('=');
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
return {...urlParams, [key]: parseInt(value)}
} else {
return {...urlParams, [key]: decodeURI(value)}
}
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment