1、更新url某一参数的值
function updateQueryStringParameter(uri, key, value) {
if (!value) { return uri }
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
2、删除url某一参数
function removeQueryStringParameter(uri, key) {
var re = new RegExp("([&]?)" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '');
}
}
3、使用
let newurl = updateQueryStringParameter(window.location.href, 'projectId', '123');
// 更新当前url,没有历史记录
window.history.replaceState({
path: newurl
}, '', newurl);
let newurl = removeQueryStringParameter(window.location.href, 'projectId');
// 更新当前url,没有历史记录
window.history.replaceState({
path: newurl
}, '', newurl);