-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsplitFilePath.ts
29 lines (23 loc) · 987 Bytes
/
splitFilePath.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export function splitFilePath(filePath: string) {
// Extract the base name (the last part of the path)
const baseName = filePath.split("/").pop();
if (!baseName) throw new Error("Invalid file path");
// Handling cases where there is no extension or the file is hidden
if (baseName === "" || baseName.startsWith(".") || !baseName.includes(".")) {
return {
pathWithoutExtension: filePath,
extension: "",
fileName: baseName,
};
}
// Finding the last dot to separate the extension
const lastDotIndex = baseName.lastIndexOf(".");
// Extracting the path without extension and the extension
const pathWithoutExtension =
filePath.substring(0, filePath.lastIndexOf(".")) ||
baseName.substring(0, lastDotIndex);
const extension = baseName.substring(lastDotIndex);
// Extracting just the file name without the extension
const fileName = baseName.substring(0, lastDotIndex);
return { pathWithoutExtension, extension, fileName };
}