How can I add or update a query string parameter?

后端 未结 27 3205
别那么骄傲
别那么骄傲 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:13

    There are a lot of awkward and unnecessarily complicated answers on this page. The highest rated one, @amateur's, is quite good, although it has a bit of unnecessary fluff in the RegExp. Here is a slightly more optimal solution with cleaner RegExp and a cleaner replace call:

    function updateQueryStringParamsNoHash(uri, key, value) {
      var re = new RegExp("([?&])" + key + "=[^&]*", "i");
      return re.test(uri)
           ? uri.replace(re, '$1' + key + "=" + value)
           : uri + separator + key + "=" + value
      ;
    }
    

    As an added bonus, if uri is not a string, you won't get errors for trying to call match or replace on something that may not implement those methods.

    And if you want to handle the case of a hash (and you've already done a check for properly formatted HTML), you can leverage the existing function instead of writing a new function containing the same logic:

    function updateQueryStringParams(url, key, value) {
        var splitURL = url.split('#');
        var hash = splitURL[1];
        var uri = updateQueryStringParamsNoHash(splitURL[0]);
        return hash == null ? uri : uri + '#' + hash;
    }
    

    Or you can make some slight changes to @Adam's otherwise excellent answer:

    function updateQueryStringParameter(uri, key, value) {
      var re = new RegExp("([?&])" + key + "=[^&#]*", "i");
      if (re.test(uri)) {
        return uri.replace(re, '$1' + key + "=" + value);
      } else {
        var matchData = uri.match(/^([^#]*)(#.*)?$/);
        var separator = /\?/.test(uri) ? "&" : "?";    
        return matchData[0] + separator + key + "=" + value + (matchData[1] || '');
      }
    }
    

提交回复
热议问题