How can I add or update a query string parameter?

后端 未结 27 2819
别那么骄傲
别那么骄傲 2020-11-22 02:35

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development

27条回答
  •  隐瞒了意图╮
    2020-11-22 03:33

    A different approach without using regular expressions. Supports 'hash' anchors at the end of the url as well as multiple question mark charcters (?). Should be slightly faster than the regular expression approach.

    function setUrlParameter(url, key, value) {
      var parts = url.split("#", 2), anchor = parts.length > 1 ? "#" + parts[1] : '';
      var query = (url = parts[0]).split("?", 2);
      if (query.length === 1) 
        return url + "?" + key + "=" + value + anchor;
    
      for (var params = query[query.length - 1].split("&"), i = 0; i < params.length; i++)
        if (params[i].toLowerCase().startsWith(key.toLowerCase() + "="))
          return params[i] = key + "=" + value, query[query.length - 1] = params.join("&"), query.join("?") + anchor;
    
      return url + "&" + key + "=" + value + anchor
    }
    

提交回复
热议问题