How can I add or update a query string parameter?

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

    Here is a shorter version that takes care of

    • query with or without a given parameter
    • query with multiple parameter values
    • query containing hash

    Code:

    var setQueryParameter = function(uri, key, value) {
      var re = new RegExp("([?&])("+ key + "=)[^&#]*", "g");
      if (uri.match(re)) 
        return uri.replace(re, '$1$2' + value);
    
      // need to add parameter to URI
      var paramString = (uri.indexOf('?') < 0 ? "?" : "&") + key + "=" + value;
      var hashIndex = uri.indexOf('#');
      if (hashIndex < 0)
        return uri + paramString;
      else
        return uri.substring(0, hashIndex) + paramString + uri.substring(hashIndex);
    }
    

    The regex description can be found here.

    NOTE: This solution is based on @amateur answer, but with many improvements.

提交回复
热议问题