See code:
var file1 ="50.xsl";
var file2 =30.doc";"
getFileExtension(file1); //returs xsl
getFileExtension(file2); //returs doc
function getFileExtension(filename) {
/*TODO*/
}
See code:
var file1 ="50.xsl";
var file2 =30.doc";"
getFileExtension(file1); //returs xsl
getFileExtension(file2); //returs doc
function getFileExtension(filename) {
/*TODO*/
}
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
edit: Strangely (or maybe it's not) the $1
in the second argument of the replace method doesn't seem to work... Sorry.
return /[^.]+$/.exec(filename);
Should do it.
Edit: In response to PhiLho's comment, use something like:
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
function getFileExtension(filename)
{
var ext = /^.+\.([^.]+)$/.exec(filename);
return ext == null ? "" : ext[1];
}
Tested with "a.b" (=> "b"), "a" (=> ""), ".hidden" (=> ""), "" (=> ""), null (=> "")
Also "a.b.c.d" (=> "d"), ".a.b" (=> "b"), "a..b" (=> "b").
function file_get_ext(filename)
{
return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
}
I just realized that it's not enough to put a comment on p4bl0's answer, though Tom's answer clearly solves the problem:
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
function extension(fname) {
var pos = fname.lastIndexOf(".");
var strlen = fname.length;
if(pos != -1 && strlen != pos+1){
var ext = fname.split(".");
var len = ext.length;
var extension = ext[len-1].toLowerCase();
}else{
extension = "No extension found";
}
return extension;
}
//usage
extension('file.jpeg')
always returns the extension lower cas so you can check it on field change works for:
file.JpEg
file (no extension)
file. (noextension)
function func() { var val=document.frm.filename.value; var arr=val.split("."); alert( arr[arr.length-1] ); var arr1=val.split("\"); alert(arr1[arr1.length-2]); if(arr[1]=="gif" || arr[1]=="bmp" || arr[1]=="jpeg") { alert("this is an image file "); } else { alert("this is not an image file"); } }