简体   繁体   English

Grunt Task-从没有扩展名的路径获取文件名

[英]Grunt Task - Get Filename from path without extension

Is it possible to get the filename without the extension from the src filepath. 是否可以从src文件路径获取不带扩展名的文件名。

As an example, let's say the src file is my-file.png - located at images/my-file.png. 例如,假设src文件是my-file.png-位于images / my-file.png。

In my task I have this at the moment: 在我的任务中,我现在有这个:

var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);

When I reference filename for output it returns: 当我引用filename进行输出时,它返回:

images/my-file.png

I want to only return the actual filename, without the path and without the extension: 我只想返回实际的文件名,而不包含路径和扩展名:

my-file.png

How can I achieve this? 我该如何实现?

Might be pretty old but if someone else finds this SO., in reply for @user3143218 's comment : slice(0, -4) will remove the last 4 characters from the name, so for the example my-file.png we will get my-file but for script.js we will get scrip . 可能已经很老了,但是如果有人发现了这个,请回复@ user3143218的注释:slice(0,-4)将从名称中删除最后4个字符,因此对于示例my-file.png我们将获取my-file但是对于script.js我们将获取scrip I suggest using a regex removing everything from the last dot. 我建议使用正则表达式删除最后一个点中的所有内容。

You could use a regex like this: 您可以使用以下正则表达式:

var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.substr(0, theFile.lastIndexOf('.')) || theFile;

That should give you my-file . 那应该给你my-file The regex gives you the string after the last forward slash, and the next line removes everything after the last dot (and the dot). 正则表达式为您提供最后一个正斜杠之后的字符串,而下一行将删除最后一个点(和该点)之后的所有内容。

Thanks to Andeersg's answer below I was able to pull this off. 多亏了Andeersg在下面的回答,我才能够做到这一点。 It might not be the best solution but it works. 它可能不是最佳解决方案,但它可以工作。 Final code is: 最终代码是:

var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.slice(0, -4);

Now onlyName will return: 现在, onlyName将返回:

my-file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM