The URLSearchParams provides an interface to work with the data in the query string of a URL.
It also allows manipulation of the query string.
Traditionally, we’ve used regexs and splitting the string to pull out each parameter from the URL. Just like this answers on Stack Overflow.
URLSearchParams API
Given a URL string, we can easily extract parameter values.
Let’s set the parameter string first and print the data using URLSearchParams.
Let’s extract the parameter values.
If there are several values for a param, get returns the first value.
We can also set the parameters. Just like this:
If there are several values, set removes all other parameters with the same name.
We can also append values.
We can also delete one or more parameters
How to modify complete URL?
The URL constructor is helpful to modify the URL.
Take a look at this example
To make actual changes to the URL, we can grab parameters, update their values, then use history.replaceState to update the URL.
// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0
Sources:
API examples query search string url URLSearchParams values