How to get the file name from a full path using JavaScript?

前端 未结 18 1203
生来不讨喜
生来不讨喜 2020-11-22 11:01

Is there a way that I can get the last value (based on the \'\\\' symbol) from a full path?

Example:

C:\\Documents and Settings\\img\\recycled log.jpg<

18条回答
  •  误落风尘
    2020-11-22 11:50

    Another one

    var filename = fullPath.split(/[\\\/]/).pop();
    

    Here split have a regular expression with a character class
    The two characters have to be escaped with '\'

    Or use array to split

    var filename = fullPath.split(['/','\\']).pop();
    

    It would be the way to dynamically push more separators into an array, if needed.
    If fullPath is explicitly set by a string in your code it need to escape the backslash!
    Like "C:\\Documents and Settings\\img\\recycled log.jpg"

提交回复
热议问题