简体   繁体   中英

Grunt Task - Get Filename from path without extension

Is it possible to get the filename without the extension from the src filepath.

As an example, let's say the src file is my-file.png - located at 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:

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 . 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 . 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. 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:

my-file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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