Javascript – Get extension from filename like variable – Javascript – jQuery

javascriptjquery

I have a varable var file = "testfile.txt"; I am using the following script to find its extension and it works well;

var parts = file.split('.');
var flename = parts[0];
var ext = parts[1];

But if i have a filename with more than one dots, the logic sucks.. It will give txt for filename.txt, but not in the case of file.nam.e.txt or something else.

Anybody suggest me the simplest solution to do this using javascript and(or) jQuery??

Thanks in advance..

Best Answer

Just so you get some alternatives, you can extract it with regular expressions too:

var full = "filename.ext.txt";

// Get all characters before the last dot
var filename = /.*(?=\.)/.exec(full);

// Get the part without dots on the end
var extension = /[^\.]*$/.exec(full);

// If there are no dots in the full name, filename will be empty and extension
// will contain the whole filename. Do some extra processing:
if(!filename){
    filename = full;
    extension = '';
}