看代码:
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*/
}
当前回答
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.slice(fileName.lastIndexOf('.'))
虽然这有一个缺点,即没有扩展名的文件将返回最后一个字符串。 但如果你这样做,这将解决所有问题:
function getExtention(fileName){
var i = fileName.lastIndexOf('.');
if(i === -1 ) return false;
return fileName.slice(i)
}
如果你正在处理web url,你可以使用:
function getExt(filepath){
return filepath.split("?")[0].split("#")[0].split('.').pop();
}
getExt("../js/logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome.to.me") // html
getExt("c:\\logs\\yesterday.log"); // log
演示:https://jsfiddle.net/squadjot/q5ard4fj/
// 获取文件后缀名 function getFileExtension(file) { var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i; var extension = file.match(regexp); return extension && extension[1]; } console.log(getFileExtension("https://www.example.com:8080/path/name/foo")); console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR")); console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment")); console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));
var filetypeArray = (file.type).split("/");
var filetype = filetypeArray[1];
在我看来,这是一个更好的方法。
对于大多数应用程序,一个简单的脚本,如
return /[^.]+$/.exec(filename);
会工作得很好(由汤姆提供)。然而,这并非万无一失。如果提供了以下文件名,它将不起作用:
image.jpg?foo=bar
这可能有点过分,但我建议使用这样的url解析器来避免由于不可预测的文件名而导致的失败。
使用这个特定的函数,你可以得到这样的文件名:
var trueFileName = parse_url('image.jpg?foo=bar').file;
这将输出“image.jpg”,不带url变量。然后您就可以获取文件扩展名了。