Get directory of a file name in Javascript

前端 未结 9 1659
囚心锁ツ
囚心锁ツ 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:31

    filepath.split("/").slice(0,-1).join("/"); // get dir of filepath
    
    1. split string into array delimited by "/"
    2. drop the last element of the array (which would be the file name + extension)
    3. join the array w/ "/" to generate the directory path

    such that

    "/path/to/test.js".split("/").slice(0,-1).join("/") == "/path/to"
    

提交回复
热议问题