8-04 1,151 views
example
updateQueryStringParameter("https://www.baidu.com?a=123",'b','hello')
//result
https://www.baidu.com/?a=123&b=hello
function updateQueryStringParameter(uri, key, value) {
if (!value) {
return uri;
}
// var reg1 = new RegExp("/" + key + "=.*?(&?)/", "g"); // 加'g',删除字符串里所有的"a"
// var url2 = uri.replace(reg1, "");
//
// alert(url2);
let url = new URL(uri);
//let inputParams = new URLSearchParams(inputUrl.search);
//console.log("The parameters of the url is defined as: ", inputParams)
url.searchParams.delete(key);
url.searchParams.append(key, value);
//inputParams.append(key, value);
//alert(url);
//alert(url)
return url;
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;
}
}