You used to have to write your own JavaScript function to get and set query string parameters, but the modern way to do it is to use URLSearchParams
.
Examples
Below are some examples of what you can do with URLSearchParams
.
const params = new URLSearchParams('cool=true&page=2');
// or use could pass in window.location.search to get the parameters for the current page
const cool = params.get('cool'); // "indeed"
const page = params.get('page'); // "1"
params.set('page', '5'); // "5"
params.append('more', 'indeed');
params.toString(); // cool=true&page=2&more=indeed
Here is everything that you can do, assuming the base is const params = new URLSearchParams('https://codeboosh.com?cool=indeed&page=2')
append
params.append('more', 'indeed');
delete
params.delete('page');
get
params.get('cool'); // true
getAll
params.getAll('cool'); // ['indeed']
has
params.has('cool'); // true
set
params.set('page', '5');
toString
params.toString(); // cool=indeed&page=5
sort
params.sort();
forEach
params.forEach(function (item) {
console.log(item);
});
keys
for (var key of params.keys()) {
console.log(key);
}
values
for (var value of params.values()) {
console.log(value);
}
Browser support
Browser support for URLSearchParams
is pretty super, with all modern browsers supporting it. However, if you need to support IE, you will have to use a polyfill.
Polyfill for IE
There are a few nice polyfills out there if you need to support IE including url-search-params-polyfill and url-search-params.