To retrieve the entire querystring from the current URL, beginning with the ?
character, you can use
location.search
https://developer.mozilla.org/en-US/docs/DOM/window.location
Example:
// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123"
In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:
/**
* 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('&')
.map(function(keyValueString) { return keyValueString.split('=') })
.reduce(function(urlParams, [key, value]) {
if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
urlParams[key] = parseInt(value);
} else {
urlParams[key] = decodeURI(value);
}
return urlParams;
}, {});
}
You can use the above like so:
// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }
// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }
// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') {
console.log(urlParams.parameterName);
}