我可以更改 URL 的最后一部分(在 URL:child中),但如果 URL 的引數存在,則這些引數會被此更改洗掉 ( ?para=1¶=2)。
有沒有辦法不洗掉引數?
樣本:
https://example.com/sub/child?para=1¶=2
JS:
const str = window.location.href;
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path "/new_child";
window.history.pushState("object or string", "Title", new_path);
window.history.replaceState("object or string", "Title", new_path);
uj5u.com熱心網友回復:
在替換最后一部分之前,您可以像這樣保存引數
var str = "https://example.com/sub/child?para=1¶=2";
var params = str.split('?')[1]
const lastIndex = str.lastIndexOf("/");
const path = str.substring(0, lastIndex);
const new_path = path "/new_child?" params;
console.log(new_path)
或者,您可以使用正則運算式創建一個函式來執行此操作
var str = "https://example.com/sub/child?para=1¶=2";
const new_path = replaceUrlPart(str, "child", "new_child")
console.log(new_path)
function replaceUrlPart(url, partToRemove, partToAdd){
return url.replace(partToRemove,partToAdd);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/427899.html
標籤:javascript 网址 链接 推状态
上一篇:如何從多維陣列中獲得最大精度?
