Get directory of a file name in Javascript

前端 未结 9 1527
囚心锁ツ
囚心锁ツ 2021-01-17 07:41

How to get the directory of a file?

For example, I pass in a string

C:\\Program Files\\nant\\bin\\nant.exe

I want a function that r

9条回答
  •  北荒
    北荒 (楼主)
    2021-01-17 08:10

    function getFileDirectory(filePath) {
      if (filePath.indexOf("/") == -1) { // windows
        return filePath.substring(0, filePath.lastIndexOf('\\'));
      } 
      else { // unix
        return filePath.substring(0, filePath.lastIndexOf('/'));
      }
    }
    console.assert(getFileDirectory('C:\\Program Files\\nant\\bin\\nant.exe') === 'C:\\Program Files\\nant\\bin');
    console.assert(getFileDirectory('/usr/bin/nant') === '/usr/bin');
    

提交回复
热议问题