我想动态更改导航栏中的特定参数。我有这个url,想要改变"通过"max"
http://mywebsite.com/?par1=mynameis&par2=pedro&par3=nicetomeetyou
通过使用这个,它删除了我所有的参数。
hello = "max"
window.history.replaceState(null, null, "?par2="+hello);
这就是我想要的:
http://mywebsite.com/?par1=mynameis&par2=max&par3=nicetomeetyou
和
http://mywebsite.com/?par1=mynameis&par2=max
使用URL接口
const hello = 'max';
// let url = new URL(location.href); // from location.href
let url = new URL(`http://mywebsite.com/?par1=mynameis&par2=pedro&par3=nicetomeetyou`); // from string
url.searchParams.set('par2',hello); // change ONE parameter
console.log(url.searchParams.toString());
window.history.replaceState(null, null, `?${url.searchParams.toString()}`);
我更喜欢从完整的URL开始,但你可以使用URLSearchParams来代替
const hello = 'max';
// let sp = new URLSearchParams(location.search); // from location.search
let sp = new URLSearchParams(`?par1=mynameis&par2=pedro&par3=nicetomeetyou`);
sp.set('par2',hello); // change ONE parameter
console.log(sp.toString());
window.history.replaceState(null, null, `?${sp.toString()}`);
您可以使用URLSearchParams
:
const params = new URLSearchParams(window.location.search); // Creates search params object
params.set('par2', hello); // Set par2 to new value
window.history.replaceState(null, null, params.toString()); // Replace url
这可能不理想,但它可以工作。
var newpar2 = "max"
var newQueryStr = window.location.search.replace(/^(.+&par2=).+?(&.+)$/, `$1${newpar2}$2`)
window.history.replaceState(null, null, newQueryStr);