How can I add or update a query string parameter?

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

    I know this is quite old but i want to fires my working version in here.

    function addOrUpdateUrlParam(uri, paramKey, paramVal) {
      var re = new RegExp("([?&])" + paramKey + "=[^&#]*", "i");
      if (re.test(uri)) {
        uri = uri.replace(re, '$1' + paramKey + "=" + paramVal);
      } else {
        var separator = /\?/.test(uri) ? "&" : "?";
        uri = uri + separator + paramKey + "=" + paramVal;
      }
      return uri;
    }
    
    jQuery(document).ready(function($) {
      $('#paramKey,#paramValue').on('change', function() {
        if ($('#paramKey').val() != "" && $('#paramValue').val() != "") {
          $('#uri').val(addOrUpdateUrlParam($('#uri').val(), $('#paramKey').val(), $('#paramValue').val()));
        }
      });
    });
    
    
    
    

    NOTE This is a modified version of @elreimundo

提交回复
热议问题