Sometimes, we want to update existing URL query string values with JavaScript.
In this article, we’ll look at how to update existing URL query string values with JavaScript.
How to update existing URL query string values with JavaScript?
To update existing URL query string values with JavaScript, we can use the URL
constructor.
For instance, we write:
const currentUrl = 'http://www.example.com/hello.png?w=100&h=100&bg=white';
const url = new URL(currentUrl);
url.searchParams.set("w", "200");
const newUrl = url.href;
console.log(newUrl);
to create a new URL
instance from currentUrl
.
Then we call url.searchParams.set
to update the w
query parameter to have value 200.
Then we get the new URL with url.href
.
Therefore, newUrl
is 'http://www.example.com/hello.png?w=200&h=100&bg=white'
.
Conclusion
To update existing URL query string values with JavaScript, we can use the URL
constructor.