How can I add or update a query string parameter?

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

    if you want to set multiple parameters at once:

    function updateQueryStringParameters(uri, params) {
        for(key in params){
          var value = params[key],
              re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
              separator = uri.indexOf('?') !== -1 ? "&" : "?";
          if (uri.match(re)) {
            uri = uri.replace(re, '$1' + key + "=" + value + '$2');
          }
          else {
            uri = uri + separator + key + "=" + value;
          }
        }
        return uri;
    }
    

    same function as @amateur's

    if jslint gives you an error add this after the for loop

    if(params.hasOwnProperty(key))
    

提交回复
热议问题