/**
* Splits a file path into its components (root, directories, filename).
*
* @param {string} filePath The file path to split.
* @returns {object} An object containing the root, directories, and filename.
* Returns null if the input is not a string.
*/
function splitFilePath(filePath) {
if (typeof filePath !== 'string') {
return null; // Handle invalid input
}
const parts = filePath.split(/[\\/]/); // Split by path separators
let root = [];
let directories = [];
let filename = parts.pop(); // Get the last part as the filename
// Reconstruct directories from the remaining parts
for (let i = 0; i < parts.length; i++) {
if (parts[i] !== "") { //avoid empty strings
directories.unshift(parts[i]); // Add directories in the correct order
}
}
return {
root: root.join('\\'), // Join root parts with backslashes
directories: directories.join('\\'), // Join directories with backslashes
filename: filename
};
}
Add your comment