Need a basename function in Javascript

I need a short basename function (one-liner ?) for Javascript:

basename("/a/folder/file.a.ext") -> "file.a"
basename("/a/folder/file.ext") -> "file"
basename("/a/folder/file") -> "file"

That should strip the path and any extension.

Update: For dot at the beginning would be nice to treat as "special" files

basename("/a/folder/.file.a.ext") -> ".file.a"
basename("/a/folder/.file.ext") -> ".file"
basename("/a/folder/.file") -> ".file" # empty is Ok
basename("/a/folder/.fil") -> ".fil"  # empty is Ok
basename("/a/folder/.file..a..") -> # does'nt matter

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.