To append parameters to the URL without refresh with JavaScript, we use the replaceState
method.
For instance, we write
const url = new URL(window.location.href);
url.searchParams.set("param1", "val1");
url.searchParams.delete("param2");
window.history.replaceState(null, null, url);
to parse the existing URL into an object with the URL
constructor.
Then we call searchParams.set
to set the param1
query parameter value to 'val1'
.
Next, we call delete
to delete the param2
query parameter.
And then we call replaceState
with the url
object automatically converted to a string to update the query string.