簡體   English   中英

使用 Javascript 從 URL 中刪除子目錄

[英]Remove subdirectory from URL with Javascript

我想從 URL ( https://testing.com/sg/features/ ) 中刪除“sg”子目錄,結果是 ( https://testing.com/features/ )。

假設我的 window.location.href 是https://testing.com/sg/features/ ,我需要編輯並從中刪除“sg”子目錄,然后將其放入新位置而不對其進行硬編碼。 這意味着它將動態獲取 URL 然后 go 到沒有“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/' 時執行 global.replace。 你的選擇

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM