使用Javascript从URL中删除子目录



我想删除;sg";URL中的子目录(https://testing.com/sg/features/),导致(https://testing.com/features/)。

假设我的window.location.hrefhttps://testing.com/sg/features/,我需要编辑并删除";sg";子目录,然后将其放在一个新的位置而不进行硬编码。这意味着它将动态地获取URL,然后转到没有"的位置;sg";(https://testing.com/features/)。

var url = 'https://testing.com/sg/features/';
var x = url.split('/');
console.log(x[3]); //result: sg

我只能从URL中获取sg,但不确定如何删除它。

我认为最好的方法是按"/"进行拆分,查找一个与要删除的字符串完全相同的部分,然后重新组合新字符串,同时忽略匹配项。此代码删除字符串中的每个/sg/

let thisLocation = "https://testing.com/sg/features/";

let splitLoc = thisLocation.split('/');
let newLocation = "";

for (let i = 0; i < splitLoc.length; i++){
if (splitLoc[i] !== "sg")
newLocation += splitLoc[i] + '/';
}

newLocation = newLocation.substring(0, newLocation.length - 1);

您也可以在查找"/sg/"时执行全局替换。您选择的

最新更新