Here would be my approach, probably not the most efficient nor the most readable, but it gets the job done :-) I wrapped it inside a function for reusability. It assumes that we pass a filename without leading path as parameter.
function getFileInfo( filename ) {
let arr = filename.split(".");
if( arr.length < 2 ) return [ filename, "" ];
return arr.reduce( (oldval, newval, currentIndex, arr) => {
return currentIndex == arr.length - 1
? [ oldval, newval ]
: oldval + "." + newval;
});
}
let [ fname, ext ] = getFileInfo( "azet.sqdsd.fsdfsd.txt" );
// filename is now in variable fname and extension in variable ext
The way this works is it splits the filename on dots. Then it concatenates the strings in the array until it arrives on the last element where it returns an array with the filename and extension.
Special cases:
- If no dots, it returns an array as
[ filename, "" ]
- If you pass a dot-file name, it returns an array as
[ "", extension ]