How can I add or update a query string parameter?

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

    Here's my slightly different approach to this, written as an excercise

    function addOrChangeParameters( url, params )
    {
      let splitParams = {};
      let splitPath = (/(.*)[?](.*)/).exec(url);
      if ( splitPath && splitPath[2] )
        splitPath[2].split("&").forEach( k => { let d = k.split("="); splitParams[d[0]] = d[1]; } );
      let newParams = Object.assign( splitParams, params );
      let finalParams = Object.keys(newParams).map( (a) => a+"="+newParams[a] ).join("&");
      return splitPath ? (splitPath[1] + "?" + finalParams) : (url + "?" + finalParams);
    }
    

    usage:

    const url = "http://testing.com/path?empty&value1=test&id=3";
    
    addOrChangeParameters( url, {value1:1, empty:"empty", new:0} )
    
    "http://testing.com/path?empty=empty&value1=1&id=3&new=0"
    

提交回复
热议问题