Need a basename function in Javascript

后端 未结 19 2030
野性不改
野性不改 2020-11-29 02:44

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

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


        
19条回答
  •  孤独总比滥情好
    2020-11-29 03:20

    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.

提交回复
热议问题