Reputation: 1636
I want to get the directory from the file path without the file name in JavaScript. I want the inputs and outputs in the following behavior.
Input: '/some/path/to/file.txt'
Output: '/some/path/to'
Input: '/some/path/to/file'
Output: '/some/path/to/file'
Input: '/some/folder.with/dot/path/to/file.txt'
Output: '/some/folder.with/dot/path/to'
Input: '/some/file.txt/path/to/file.txt'
Output: '/some/file.txt/path/to'
I was thinking of doing this using RegExp
. But, not sure how the exact RegExp should be written.
Can someone help me with an EFFICIENT solution other than that or the RegExp?
Upvotes: 2
Views: 239
Reputation: 784928
Looking at your examples looks like you want to treat anything except last filename as directory name where filename always contains a dot.
To get that part, you can use this code in Javascript:
str = str.replace(/\/\w+\.\w+$/, "");
Regex \/\w+\.\w+$
matches a /
and 1+ word characters followed by a dot followed by another 1+ word characters before end of string. Replacement is just an empty string.
However, do keep in mind that some filenames may not contain any dot character and this replacement won't work in those cases.
Upvotes: 3
Reputation: 25398
You could use lastIndexOf to get the index and then use slice to get the desired result.
const strArr = [
"/some/path/to/file.txt",
"/some/path/to/file",
"/some/folder.with/dot/path/to/file.txt",
"/some/file.txt/path/to/file.txt",
];
const result = strArr.map((s) => {
if (s.match(/.txt$/)) {
const index = s.lastIndexOf("/");
return s.slice(0, index !== -1 ? index : s.length);
} else return s;
});
console.log(result);
Using regex
const strArr = [
"/some/path/to/file.txt",
"/some/path/to/file",
"/some/folder.with/dot/path/to/file.txt",
"/some/file.txt/path/to/file.txt",
];
const result = strArr.map((s) => s.replace(/\/\w+\.\w+$/, ""));
console.log(result);
Upvotes: 1