![](/img/trans.png)
[英](Javascript) How to extract the last part of the current URL - without the file extension?
[英]How to extract last directory and file name from URL in javascript?
我需要從這樣的圖像中提取最后一個子目錄和文件名(子目錄名和 的位置不一致):
example.com/dw/image/v2/BFKH_PRD/on/ demandware.static /-/ Library- Sites-RefArchSharedLibrary / default / dw981dad25 / Homepage / 2021 / 11_NOV / 1102 / HPNAVTILES / 1102_WGA_NAV_TILES &q= 10jpg &q= 10jpg
我正在使用這個js來提取文件名,效果很好,但我不知道如何獲取最后一個子目錄。
function() {
var url = {{INSERT URL}};
return url.substr(url.lastIndexOf('/')+1).split('?')[0];
}
謝謝一堆!
如果你的 URL 被保證是有效的——並且從一個協議開始——我會嘗試盡可能少地解析自己。 這是一種解決方案:
url = 'https://example.com/dw/image/v2/BFKH_PRD/on/demandware.static/-/Library-Sites-RefArchSharedLibrary/default/dw981dad25/Homepage/2021/11_NOV/1102/HPNAVTILES/1102_WGA_NAV_TILES_01_01.jpg?sw=40&q=100';
const lastDirectory = (url) => {
const parsed = new URL(url);
const path = parsed.pathname.split('/');
return path.slice(-2).join('/');
};
console.log(lastDirectory(url));
通過使用 JavaScript 的URL()
,我們不必自己處理刪除查詢字符串(或 URL 的其他部分):我們可以輕松地提取路徑並對其執行我們的操作。
輸出:
HPNAVTILES/1102_WGA_NAV_TILES_01_01.jpg
你可以像這樣得到最后一個子目錄
function() {
var url = {{INSERT URL}};
directories = url.split("/")
lastSubdirectory = directories[directories.length - 2]
return lastSubdirectory
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.