从URL和Strip File扩展名获取文件名



我只需要在没有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"?

预先感谢。

您可以使用JavaScript进行以下操作。pop返回一个字符串的最后一个元素,然后您可以使用替换函数在末端获取没有.html的文件名。

function getFilename () {
  return {{ Page Path }}.split('/').pop().replace('.html', '');
}

我看到{{page path}}可能是某种模板语言,但是您可以修改上述脚本,以获取当前的URL,然后获取文件名。

function getFilename () {
  return window.location.href.split('/').pop().replace('.html', '');
}

此外,您可以使以下任何文件扩展名更加动态。您需要使用索引索引,然后从文件名开始到该期间的位置。

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));

function () {
var value={{Page Path}}.split("/");
var fileName= value.reverse()[0].split('.')[0];
return fileName;
 }

如果您需要摆脱任何扩展名,则可以使用带有正则表达式的.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 to index.php以及 test.name.with.dots.txt-> test.name.with.dots

短而甜:

"https://url/to/file/solo-pack.html".split(/[\/]/).pop().replace(/.[^/.]+$/, "")

返回:

solo-pack

最新更新