Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 744
PeterMmm Avatar asked Sep 29 '10 09:09

PeterMmm


People also ask

What is basename function?

The basename() function returns the filename from a path.

What is basename in path?

The path. basename() method returns the filename part of a file path.

How do I find the filename in node JS?

In NodeJS, __filename. split(/\|//). pop() returns just the file name from the absolute file path on any OS platform.


1 Answers

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.

like image 59
Tomo Huynh Avatar answered Sep 22 '22 11:09

Tomo Huynh