Need a basename function in Javascript

后端 未结 19 2012
野性不改
野性不改 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条回答
  •  萌比男神i
    2020-11-29 03:31

    Defining a flexible basename implementation

    Despite all the answers, I still had to produce my own solution which fits the following criteria:

    1. Is fully portable and works in any environment (thus Node's path.basename won't do)
    2. Works with both kinds of separators (/ and \)
    3. Allows for mixing separators - e.g. a/b\c (this is different from Node's implementation which respects the underlying system's separator instead)
    4. Does not return an empty path if path ends on separator (i.e. getBaseName('a/b/c/') === 'c')

    Code

    (make sure to open the console before running the Snippet)

    /**
     * Flexible `basename` implementation
     * @see https://stackoverflow.com/a/59907288/2228771
     */
    function getBasename(path) {
      // make sure the basename is not empty, if string ends with separator
      let end = path.length-1;
      while (path[end] === '/' || path[end] === '\\') {
        --end;
      }
    
      // support mixing of Win + Unix path separators
      const i1 = path.lastIndexOf('/', end);
      const i2 = path.lastIndexOf('\\', end);
    
      let start;
      if (i1 === -1) {
        if (i2 === -1) {
          // no separator in the whole thing
          return path;
        }
        start = i2;
      }
      else if (i2 === -1) {
        start = i1;
      }
      else {
        start = Math.max(i1, i2);
      }
      return path.substring(start+1, end+1);
    }
    
    // tests
    console.table([
      ['a/b/c', 'c'],
      ['a/b/c//', 'c'],
      ['a\\b\\c', 'c'],
      ['a\\b\\c\\', 'c'],
      ['a\\b\\c/', 'c'],
      ['a/b/c\\', 'c'],
      ['c', 'c']
    ].map(([input, expected]) => {
      const result = getBasename(input);
      return {
        input, 
        result,
        expected,
        good: result === expected ? '✅' : '❌'
      };
    }));

提交回复
热议问题