//获取替换url参数后的url数据 function GetReplaceUrl(paramName, replaceWith) { var oUrl = this.location.href.toString(); var re = eval('/(' + paramName + '=)([^&]*)/gi'); var nUrl = oUrl.replace(re, paramName + '=' + replaceWith); return nUrl; }; //替换url不刷新 function ReplaceUrl(paramName, replaceWith) { window.history.replaceState(null, null, GetReplaceUrl(paramName, replaceWith)); };
ReplaceUrl("id", 3);
将url中id替换为3
如果没有自动添加,有的话自动替换,完善代码如下
//获取替换url参数后的url数据 function GetReplaceUrl(paramName, replaceWith) { var oUrl = this.location.href.toString(); var re = eval('/(' + paramName + '=)([^&]*)/gi'); if (oUrl.search(re) > 0) var nUrl = oUrl.replace(re, paramName + '=' + replaceWith); else { if(oUrl.indexOf('?')>0) nUrl = oUrl + "&" + paramName + "=" + replaceWith; else nUrl = oUrl + "?" + paramName + "=" + replaceWith; } return nUrl; };