Posted in 1 year and 8 months ago

How to change URL query parameter with Javascript

URL query parameters can be easily modified using URLSearchParams and History interfaces:

// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
Set new or modify existing parameter value. queryParams.set("myParam", "myValue");
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());


Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:

history.pushState(null, null, "?"+queryParams.toString());

 

Tags:
JavaScript
Published on 06 Apr, 2022
Last edit on 15 Dec, 2023