[英]Get Filename from URL and Strip File Extension
我只需要從 url 獲取沒有擴展名的文件名,但無法完全到達那里。
這是我有問題的網址: https ://www.mealenders.com/shop/index.php/shop/solo-pack.html
這是我嘗試過的:
function () {
var value={{Page Path}}.split("/");
return value.reverse()[0];
}
這幾乎讓我到達那里,因為它返回“solo-pack.html”。 為此,我還需要做什么才能擺脫“.html”?
提前致謝。
您可以使用 javascript 執行以下操作。 Pop返回最后一個元素,它是一個字符串,然后您可以使用replace函數來獲取末尾沒有 .html 的文件名。
function getFilename () {
return {{ Page Path }}.split('/').pop().replace('.html', '');
}
我看到 {{ Page Path }} 可能是某種模板語言,但您可以修改上面的腳本,以獲取當前 URL,然后獲取文件名。
function getFilename () {
return window.location.href.split('/').pop().replace('.html', '');
}
此外,您可以使用以下內容使其更加動態地處理任何文件擴展名。 您需要使用indexOf獲取句點的索引,然后從文件名的開頭到句點位置獲取子字符串。
function getFilename () {
var filename = window.location.href.split('/').pop();
return filename.substr(0, filename.lastIndexOf('.');
}
function getFileName(url) { return url.split("/").pop().split(".")[0]; } var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html"; console.log(getFileName(url));
我只需要從URL中獲取不帶擴展名的文件名,就不能到達那里。
這是我有問題的網址: https : //www.mealenders.com/shop/index.php/shop/solo-pack.html
這是我嘗試過的:
function () {
var value={{Page Path}}.split("/");
return value.reverse()[0];
}
這幾乎讓我到達那里,因為它返回“ solo-pack.html”。 我還需要做些什么來擺脫“ .html”呢?
提前致謝。
如果您需要刪除任何擴展名,您可以使用.replace()
和正則表達式:
var url = "https://www.mealenders.com/shop/index.php/shop/solo-pack.html"; function getFilename (path) { return path.toString().split('/').pop().replace(/\.\w+$/, ''); } console.log(getFilename(url));
例如,這會將 test/index.html 更改為index
,但將index.php.default
更改為index.php
以及test.name.with.dots.txt
-> test.name.with.dots
function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
}
簡短而甜美:
"https://url/to/file/solo-pack.html".split(/[\\/]/).pop().replace(/\.[^/.]+$/, "")
退貨:
solo-pack
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.