Need a basename function in Javascript
function basename(path) {
return path.split('/').reverse()[0];
}
Breaks up the path into component directories and filename then returns the last piece (the filename) which is the last element of the array.
function baseName(str)
{
var base = new String(str).substring(str.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1)
base = base.substring(0, base.lastIndexOf("."));
return base;
}
If you can have both /
and \
as separators, you have to change the code to add one more line
Any of the above works although they have no respect for speed/memory :-).
A faster/simpler implementation should uses as fewer functions/operations as possible. RegExp is a bad choice because it consumes a lot of resources when actually we can achieve the same result but easier.
An implementation when you want the filename including extension (which in fact this is the genuine definition of basename):
function basename(str, sep) {
return str.substr(str.lastIndexOf(sep) + 1);
}
If you need a custom basename implementation that has to strip also the extension I would recommend instead a specific extension-stripping function for that case which you can call it whenever you like.
function strip_extension(str) {
return str.substr(0,str.lastIndexOf('.'));
}
Usage example:
basename('file.txt','/'); // real basename
strip_extension(basename('file.txt','/')); // custom basename
They are separated such that you can combine them to obtain 3 different things: stripping the extention, getting the real-basename, getting your custom-basename. I regard it as a more elegant implementation than others approaches.
Maybe try to use existing packages if you can. http://nodejs.org/api/path.html
var path = require('path');
var str = '/path/to/file/test.html'
var fileNameStringWithoutExtention = path.basename(str, '.html');
// returns 'test'
// let path determine the extension
var fileNameStringWithoutExtention = path.basename(str, path.extname(str));
// returns 'test'
Other examples:
var pathString = path.dirname(str);
var fileNameStringWithExtention = path.basename(str);
var fullPathAndFileNameString = path.join(pathString, fileNameString);