首页 > 解决方案 > 使用 Javascript 从 URL 中删除子目录

问题描述

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

假设我的 window.location.href 是https://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,但不知道如何删除它。

标签: javascriptsplitsubstringsubdirectory

解决方案


我想说最好的方法是用'/'分割,寻找一个正是你要删除的字符串的部分,然后在忽略匹配项的同时重新组合新字符串。此代码删除字符串中的每个 /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。你的选择


推荐阅读