JSFiddle - React, Tailwind, and code Playground
by Alphonsio
JavaScript
function splitFileName(fileName) {
// Get the extension with a regular expression
const ext = /(?:\.([^.]+))?$/.exec(fileName);
// If there is no extension, return the filename with no extension
if (ext[1] === undefined) return [fileName, ''];
// Get the file name without extension
const name = fileName.slice(0, -ext[0].length);
// Return an array with name and extension
return [name, ext[1]]
}
console.log(splitFileName('filename.txt')); // ["filename", "txt"]
console.log(splitFileName('file.name.txt')); // ["file.name", "txt"]
console.log(splitFileName('filename')); // ["filename", ""]
console.log(splitFileName('file.name.with.dots.txt')); // ["file.name.with.dots", "txt"]
console.log(splitFileName('.htaccess')); // ["", "htaccess"]
console.log(splitFileName('')); // ["", ""]