看代码:
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*/
}
当前回答
我刚刚意识到,对p4bl0的回答发表评论是不够的,尽管Tom的回答显然解决了问题:
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
其他回答
fetchFileExtention(fileName) {
return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
我已经晚了很多个月,但为了简单起见,我使用了这样的东西
var 文件名 = “I.Am.文件名.docx”; var nameLen = fileName.length; var lastDotPos = fileName.lastIndexOf(“.”); var 文件名子 = 假; if(lastDotPos === -1) { 文件名子 = 假; } 还 { 如果希望“.”也保留,请删除 +1 fileNameSub = fileName.substr(lastDotPos + 1, nameLen); } document.getElementById(“showInMe”).innerHTML = fileNameSub; <div id=“showInMe”></div>
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的解决方案不能处理边缘情况。
一行解决方案,也将考虑查询参数和url中的任何字符。
string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg