Add or update URL query parameter in Javascript

Create the following function in Javascript to add or update URL query parameter.

function addOrUpdateURLParam (key, value) {
    const searchParams = new URLSearchParams(window.location.search)
    searchParams.set(key, value)
    const newRelativePathQuery = window.location.pathname + "?" + searchParams.toString()
    history.pushState(null, "", newRelativePathQuery)
}

Now, whenever you want to add or update the URL, simply call the function in the following way:

addOrUpdateURLParam("name", "adnan-tech.com")

The first parameter will be the key of the parameter, and the second will be the value.

window.location.search: will return all the query parameters starting from “?”.

URLSearchParams: This will create an instance of URLSearchParams that will be used to manipulate URL query parameters.

searchParams.set(key, value): This will set the key value provided in arguments, but will not display yet in the URL.

window.location.pathname: It returns the relative path starting from “/your_website”. It DOES NOT include the query parameters starting from “?”.

searchParams.toString(): Will convert all the key-value pairs to a string. If there will multiple parameters set, then they will be separated by the “&” sign.

history.pushState: Will actually display the query parameters in the URL.

The first parameter to the “history.pushState” function is the “state”. It can be a push, pop, or null. The second parameter is not used anymore but not removed either, passing an empty string is safe. The third parameter is the new URL, here we are passing our new string variable to set the new URL with query parameters. More information can be found here.

Video tutorial:

Following this tutorial, I hope you will be able to add or update query parameter in your website’s URL using Javascript. If it helps, check out our tutorials on Javascript.