Search code examples
javascriptjqueryurl

Merging URLSearchParams back into URL object


I have recently started using the URL object to modify URLs in javascript. I am struggling to find any documentation on the procedure I am currently trying to complete though, which is modifying a query string using a URLSearchParams object and then merging that back into the URL object

    if (~url.toLowerCase().indexOf("page=")) {
        var cleanseUrl = new URL(newUrl);
        var params = new URLSearchParams(cleanseUrl.search);
        params.delete("page");
        cleanseUrl.searchParams.set(params);
        redirectUrl = cleanseUrl.href;
    }

    window.location.replace(redirectUrl)

This is currently throwing an obvious error on the cleanseUrl.searchParams.set(params) line since this function requires two parameters and is for setting individual parameters


Solution

  • Try this

    if (newUrl.toLowerCase().includes("page=")) {
      let cleanseUrl = new URL(newUrl); 
      // delete the 'page' parameter using URLSearchParams
      cleanseUrl.searchParams.delete("page");
      window.location.replace(cleanseUrl.href);
    }