To split a file name into the name and extension, you can use the following function:
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]]
}
The above function works with the following filenames (outputs are displayed in the console):
splitFileName('filename.txt'); // ["filename", "txt"]
splitFileName('file.name.txt'); // ["file.name", "txt"]
splitFileName('filename'); // ["filename", ""]
splitFileName('file.name.with.dots.txt'); // ["file.name.with.dots", "txt"]
splitFileName('.htaccess'); // ["", "htaccess"]
splitFileName(''); // ["", ""]
Here is an online running code:
In Node.js, you can use path.parse()
:
var path = require('path');
var fileName = "filename.txt";
console.log(path.parse(fileName).name); // filename
console.log(path.parse(fileName).ext); // txt