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<
If anyone is looking for a windows absolute path (and relative path) javascript regular expression in javascript for files:
var path = "c:\\my-long\\path_directory\\file.html";
((/(\w?\:?\\?[\w\-_\\]*\\+)([\w-_]+)(\.[\w-_]+)/gi).exec(path);
Output is:
[
"c:\my-long\path_directory\file.html",
"c:\my-long\path_directory\",
"file",
".html"
]
I use @"[^\\]+$"
That gives the filename including the extension.
Does this work...
.*\/(.+)$
Posting here so I can get feedback
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))
This will get the filename but will also get the dot. You might want to truncate the last digit from it in your code.
[\w-]+\.
Update
@Geoman if you have spaces in file name then use the modified pattern below
[ \w-]+\. (space added in brackets)
Demo
Here's a slight modification to Angelo's excellent answer that allows for spaces in the path, filename and extension as well as missing parts:
function parsePath (path) {
var parts = (/(\w?\:?\\?[\w\-_ \\]*\\+)?([\w-_ ]+)?(\.[\w-_ ]+)?/gi).exec(path);
return {
path: parts[0] || "",
folder: parts[1] || "",
name: parts[2] || "",
extension: parts[3] || "",
};
}