logo
post image

How to Change URL Query Parameters with Javascript

Search query parameters can be added, updated or deleted using Javascript URL and URLSearchParams objects.

To know how to get query parameters using URL and URLSearchParams, refer the tutorial Get URL Parameters with Javascript.

Edit / Update a Parameter

The value of a parameter can be updated with the set() method of URLSearchParams object.

After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.

The final new url can then be retrieved with the toString() method of the URL object.

var url = new URL('http://demourl.com/path?id=100&topic=main');
var search_params = url.searchParams;

// new value of "id" is set to "101"
search_params.set('id', '101');

// change the search property of the main url
url.search = search_params.toString();

// the new url string
var new_url = url.toString();

// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);

Add a New Parameter

  • The set() method can be used to add a new parameter — the parameter is added if it does exist, otherwise its value is changed.

    var url = new URL('http://demourl.com/path?id=100');
    var search_params = url.searchParams;
    
    // add "topic" parameter
    search_params.set('topic', 'main');
    
    url.search = search_params.toString();
    
    var new_url = url.toString();
    
    // output : http://demourl.com/path?id=100&topic=main
    console.log(new_url);
    
  • To add a parameter that has multiple values use the append() method.

    var url = new URL('http://demourl.com/path?topic=main');
    var search_params = url.searchParams;
    
    search_params.append('id', '101');
    search_params.append('id', '102');
    
    url.search = search_params.toString();
    
    var new_url = url.toString();
    
    // output : http://demourl.com/path?id=100&id=101&id=102&topic=main
    console.log(new_url);
    

Delete a Parameter By Name

The delete() method can be used to remove a parameter from the url.

search_params.delete('id');

Remove All Parameters

All query parameters can be cleared from the url by setting search property of the URL object to blank.

var url = new URL('http://demourl.com/path?topic=main');

// set search property to blank
url.search = '';

var new_url = url.toString();

// output : http://demourl.com/path
console.log(new_url);