仅替换 URL 中的最后一个路径部分而不是参数
Replace only last path part in URL not parametres
我可以更改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);
在替换最后一部分之前,您可以像这样保存参数
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);
}
我可以更改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);
在替换最后一部分之前,您可以像这样保存参数
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);
}