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

前端 未结 18 1298
生来不讨喜
生来不讨喜 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 11:36

    This solution is much simpler and generic, for both 'file name' and 'path'.

    const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
    
    // regex to split path to two groups '(.*[\\\/])' for path and '(.*)' for file name
    const regexPath = /^(.*[\\\/])(.*)$/;
    
    // execute the match on the string str
    const match = regexPath.exec(str);
    if (match !== null) {
        // we ignore the match[0] because it's the match for the hole path string
        const filePath = match[1];
        const fileName = match[2];
    }
    

提交回复
热议问题