看代码:
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*/
}
当前回答
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
其他回答
我刚刚意识到,对p4bl0的回答发表评论是不够的,尽管Tom的回答显然解决了问题:
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}
这个简单的解决方案
function extension(filename) {
var r = /.+\.(.+)$/.exec(filename);
return r ? r[1] : null;
}
测试
/* tests */ test('cat.gif', 'gif'); test('main.c', 'c'); test('file.with.multiple.dots.zip', 'zip'); test('.htaccess', null); test('noextension.', null); test('noextension', null); test('', null); // test utility function function test(input, expect) { var result = extension(input); if (result === expect) console.log(result, input); else console.error(result, input); } function extension(filename) { var r = /.+\.(.+)$/.exec(filename); return r ? r[1] : null; }
在path模块中有一个标准库函数:
import path from 'path';
console.log(path.extname('abc.txt'));
输出:
. txt
所以,如果你只想要格式:
path.extname('abc.txt').slice(1) // 'txt'
如果没有扩展名,函数将返回一个空字符串:
path.extname('abc') // ''
如果使用Node,则path是内置的。如果你的目标是浏览器,那么Webpack将为你捆绑一个路径实现。如果你的目标浏览器没有Webpack,那么你可以手动包含path-browserify。
没有理由进行字符串分割或正则表达式。
快速和正确的路径工作
(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
一些边缘情况
/path/.htaccess => null
/dir.with.dot/file => null
使用split的解决方案很慢,使用lastIndexOf的解决方案不能处理边缘情况。