假如当前地址栏链接为:https://test.com/?type=students&page=3
//定义替换参数的方法
function changeURLArg(url,arg,arg_val){
var pattern=arg+'=([^&]*)';
var replaceText=arg+'='+arg_val;
if(url.match(pattern)){
var tmp='/('+ arg+'=)([^&]*)/gi';
tmp=url.replace(eval(tmp),replaceText);
return tmp;
}else{
if(url.match('[\?]')){
return url+'&'+replaceText;
}else{
return url+'?'+replaceText;
}
}
return url+'\n'+arg+'\n'+arg_val;
}
var thisurl=window.location.href; //https://test.com/?type=students&page=3
var newurl=changeURLArg(thisurl,'page','10');
alert(newurl); //https://test.com/?type=students&page=10
var newurl2=changeURLArg(thisurl,'type','teachers');
alert(newurl2); //https://test.com/?type=teachers&page=3