Need a basename function in Javascript

后端 未结 19 2042
野性不改
野性不改 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:08

    Fairly simple using regex:

    function basename(input) {
       return input.split(/\.[^.]+$/)[0];
    }
    

    Explanation:

    Matches a single dot character, followed by any character except a dot ([^.]), one or more times (+), tied to the end of the string ($).

    It then splits the string based on this matching criteria, and returns the first result (ie everything before the match).

    [EDIT] D'oh. Misread the question -- he wants to strip off the path as well. Oh well, this answers half the question anyway.

提交回复
热议问题