Search code examples
javascriptjqueryregexfile-type

javascript get file type only works if file has 1 dot in name


I am getting the file name which includes the type from an html input,

var file = jQuery('#attachment')[0].files[0];
var fileType = file.name.substr(file.name.indexOf(".") + 1);

and this works great if the file name is FILE.TYPE but if the file name if FIlE.Name.TYPE it does not work correctly.

How can I make sure I get the last dot before the file type? Or is there a better way to go about getting the file type?


Solution

  • indexOf always goes from left to right and get the first match. Fortunately, there is the opposite method which goes from right to left. That method is called .lastIndexOf().

    var fileType = file.name.substr(file.name.lastIndexOf(".") + 1);