Menü schliessen
Created: December 15th 2023
Last updated: March 16th 2024
Categories: Common Web Development,  JavaScript Development
Author: Tim Fürer

JavaScript: How to change URL GET parameters

Tags:  function,  Javascript
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

This JavaScript function allows you to effortlessly modify URL parameters without reloading the page.


Helper Function

function change_url_parameter(field, value) {
    let url = new URL(window.location.href);

    if ((value ?? null) !== null) {
        url.searchParams.set(field, value);
    } else {
        url.searchParams.delete(field);
    }

    window.history.replaceState({}, null, url);
}
  1. change_url_parameter(field, value): This is the function declaration, accepting two parameters:
    • field: The name of the parameter to be modified.
    • value: The new value to be assigned to the parameter. If null, the parameter will be removed from the URL.
  2. let url = new URL(window.location.href): This line initializes a new URL object using the current page's URL.
  3. if ((value ?? null) !== null) { ... }: This conditional statement checks if a new value is provided for the parameter. The ?? operator is the nullish coalescing operator, ensuring that null or undefined are treated the same.
  4. url.searchParams.set(field, value): If a value is provided, this line sets or updates the specified parameter with the given value.
  5. else { url.searchParams.delete(field) }: If no value is provided (i.e., null), this line removes the specified parameter from the URL.
  6. window.history.replaceState({}, null, url): Finally, this line updates the URL in the browser's history without reloading the page, thereby reflecting the changes made to the URL parameters.