使用 Javascript 从 URL 中删除子目录

Remove subdirectory from URL with Javascript

我想从 URL (https://testing.com/sg/features/), resulting in (https://testing.com/features/) 中删除“sg”子目录。

假设我的 window.location.href 是 https://testing.com/sg/features/, I need to edit and remove "sg" subdirectory from it, and then put it into a new location without hardcoding it. Meaning that it will dynamically get the URL and then go to the location without "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/”时执行全局 .replace。您的选择