Search code examples
javascripturlweb-applications

How to add a parameter to the URL?


My current URL is: http://something.com/mobiles.php?brand=samsung

Now when a user clicks on a minimum price filter (say 300), I want my URL to become

http://something.com/mobiles.php?brand=samsung&priceMin=300

In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.

Note: If no parameters are set then the function should add ? instead of &

i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300 instead of http://something.com/mobiles.php&priceMin=300


Solution

  • try something like this, it should consider also cases when you already have that param in url:

    function addOrUpdateUrlParam(name, value)
    {
      var href = window.location.href;
      var regex = new RegExp("[&\\?]" + name + "=");
      if(regex.test(href))
      {
        regex = new RegExp("([&\\?])" + name + "=\\d+");
        window.location.href = href.replace(regex, "$1" + name + "=" + value);
      }
      else
      {
        if(href.indexOf("?") > -1)
          window.location.href = href + "&" + name + "=" + value;
        else
          window.location.href = href + "?" + name + "=" + value;
      }
    }
    

    then you invoke it like in your case:

    addOrUpdateUrlParam('priceMin', 300);