How to add parameters to a URL that already contains other parameters and maybe an anchor

后端 未结 9 785
逝去的感伤
逝去的感伤 2020-12-05 19:36

I\'m wondering how I can add a new parameter to an existing url. The problem is: the url may also contain an anchor.

For example:

http://www.example         


        
9条回答
  •  被撕碎了的回忆
    2020-12-05 20:22

    This can be another good solution, this version is even able to replace the parameter if it already exists, add parameter without value:

    function addParam(url, param, value) {
       var a = document.createElement('a'), regex = /(?:\?|&|&)+([^=]+)(?:=([^&]*))*/g;
       var match, str = []; a.href = url; param = encodeURIComponent(param);
       while (match = regex.exec(a.search))
           if (param != match[1]) str.push(match[1]+(match[2]?"="+match[2]:""));
       str.push(param+(value?"="+ encodeURIComponent(value):""));
       a.search = str.join("&");
       return a.href;
    }
    
    url = "http://www.example.com#hashme";
    newurl = addParam(url, "ciao", "1");
    alert(newurl);
    

    http://jsfiddle.net/bknE4/81/

提交回复
热议问题