Regex for extracting filename from path

前端 未结 17 699
时光取名叫无心
时光取名叫无心 2020-12-03 01:02

I need to extract just the filename (no file extension) from the following path....

\\\\my-local-server\\path\\to\\this_file may_contain-any&character.pdf<

17条回答
  •  孤城傲影
    2020-12-03 01:27

    I'm using this regex to replace the filename of the file with index. It matches a contiguous string of characters that doesn't contain a slash and is followed by a . and a string of word characters at the end of the string. It will retrieve the filename including spaces and dots but will ignore the full file extension.

    const regex = /[^\\/]+?(?=\.\w+$)/
    
    console.log('/path/to/file.png'.match(regex))
    console.log('/path/to/video.webm'.match(regex))
    console.log('/path/to/weird.file.gif'.match(regex))
    console.log('/path with/spaces/and file.with.spaces'.match(regex))

提交回复
热议问题