Need a basename function in Javascript

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

    Contrary to misinformation provided above, regular expressions are extremely efficient. The caveat is that, when possible, they should be in a position so that they are compiled exactly once in the life of the program.

    Here is a solution that gives both dirname and basename.

    const rx1 = /(.*)\/+([^/]*)$/;    // (dir/) (optional_file)
    const rx2 = /()(.*)$/;            // ()     (file)
    
    function dir_and_file(path) {
      // result is array with
      //   [0]  original string
      //   [1]  dirname
      //   [2]  filename
      return rx1.exec(path) || rx2.exec(path);
    }
    // Single purpose versions.
    function dirname(path) {
      return (rx1.exec(path) || rx2.exec(path))[1];
    }
    function basename(path) {
      return (rx1.exec(path) || rx2.exec(path))[2];
    }
    

    As for performance, I have not measured it, but I expect this solution to be in the same range as the fastest of the others on this page, but this solution does more. Helping the real-world performance is the fact that rx1 will match most actual paths, so rx2 is rarely executed.

    Here is some test code.

    function show_dir(parts) {
      console.log("Original str :"+parts[0]);
      console.log("Directory nm :"+parts[1]);
      console.log("File nm      :"+parts[2]);
      console.log();
    }
    show_dir(dir_and_file('/absolute_dir/file.txt'));
    show_dir(dir_and_file('relative_dir////file.txt'));
    show_dir(dir_and_file('dir_no_file/'));
    show_dir(dir_and_file('just_one_word'));
    show_dir(dir_and_file('')); // empty string
    show_dir(dir_and_file(null)); 
    

    And here is what the test code yields:

    # Original str :/absolute_dir/file.txt
    # Directory nm :/absolute_dir
    # File nm      :file.txt
    # 
    # Original str :relative_dir////file.txt
    # Directory nm :relative_dir
    # File nm      :file.txt
    # 
    # Original str :dir_no_file/
    # Directory nm :dir_no_file
    # File nm      :
    # 
    # Original str :just_one_word
    # Directory nm :
    # File nm      :just_one_word
    # 
    # Original str :
    # Directory nm :
    # File nm      :
    # 
    # Original str :null
    # Directory nm :
    # File nm      :null
    

    By the way, "node" has a built in module called "path" that has "dirname" and "basename". Node's "path.dirname()" function accurately imitates the behavior of the "bash" shell's "dirname," but is that good? Here's what it does:

    1. Produces '.' (dot) when path=="" (empty string).
    2. Produces '.' (dot) when path=="just_one_word".
    3. Produces '.' (dot) when path=="dir_no_file/".

    I prefer the results of the function defined above.

    0 讨论(0)
提交回复
热议问题