您需要调整的基本实现如下所示:
function insertParam(key, value){ key = enpreURI(key); value = enpreURI(value); var kvp = document.location.search.substr(1).split('&'); var i=kvp.length; var x; while(i--) { x = kvp[i].split('='); if (x[0]==key) { x[1] = value; kvp[i] = x.join('='); break; } } if(i<0) {kvp[kvp.length] = [key,value].join('=');} //this will reload the page, it's likely better to store this until finished document.location.search = kvp.join('&'); }这大约是正则表达式或基于搜索的解决方案的两倍,但是这完全取决于查询字符串的长度和任何匹配项的索引
我为完成测试而基准的慢速正则表达式方法(慢了大约+ 150%)
function insertParam2(key,value){ key = enpreURIComponent(key); value = enpreURIComponent(value); var s = document.location.search; var kvp = key+"="+value; var r = new RegExp("(&|\?)"+key+"=[^&]*"); s = s.replace(r,"$1"+kvp); if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;}; //again, do what you will here document.location.search = s;}


