看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
当前回答
对于大多数应用程序,一个简单的脚本,如
return /[^.]+$/.exec(filename);
会工作得很好(由汤姆提供)。然而,这并非万无一失。如果提供了以下文件名,它将不起作用:
image.jpg?foo=bar
这可能有点过分,但我建议使用这样的url解析器来避免由于不可预测的文件名而导致的失败。
使用这个特定的函数,你可以得到这样的文件名:
var trueFileName = parse_url('image.jpg?foo=bar').file;
这将输出“image.jpg”,不带url变量。然后您就可以获取文件扩展名了。
其他回答
function getFileExtension(filename)
{
var ext = /^.+\.([^.]+)$/.exec(filename);
return ext == null ? "" : ext[1];
}
测试了
"a.b" (=> "b")
"a" (=> "")
".hidden" (=> "")
"" (=> "")
null (=> "")
也
"a.b.c.d" (=> "d")
".a.b" (=> "b")
"a..b" (=> "b")
快速和正确的路径工作
(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
一些边缘情况
/path/.htaccess => null
/dir.with.dot/file => null
使用split的解决方案很慢,使用lastIndexOf的解决方案不能处理边缘情况。
function file_get_ext(filename)
{
return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
}
fetchFileExtention(fileName) {
return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
var file = "hello.txt";
var ext = (function(file, lio) {
return lio === -1 ? undefined : file.substring(lio+1);
})(file, file.lastIndexOf("."));
// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello