How to add a parameter to the URL?

后端 未结 9 1017
遇见更好的自我
遇见更好的自我 2020-11-30 06:37

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

9条回答
  •  悲&欢浪女
    2020-11-30 07:18

    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);
    

提交回复
热议问题