看代码:
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*/
}
当前回答
快速和正确的路径工作
(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()
一些边缘情况
/path/.htaccess => null
/dir.with.dot/file => null
使用split的解决方案很慢,使用lastIndexOf的解决方案不能处理边缘情况。
其他回答
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
编辑:奇怪的是(或者可能不是)替换方法的第二个参数中的$1似乎不工作…对不起。
// 获取文件后缀名 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"));
如果你正在寻找一个特定的扩展名,并且知道它的长度,你可以使用substr:
var file1 = "50.xsl";
if (file1.substr(-4) == '.xsl') {
// do something
}
JavaScript参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
function file_get_ext(filename)
{
return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
}
更新编辑:自从这个问题最初发布以来,很多事情都发生了变化——wallacer修改后的答案中有很多非常好的信息,VisioN也有很好的细分
编辑:因为这是公认的答案;Wallacer的回答确实好得多:
return filename.split('.').pop();
我以前的回答是:
return /[^.]+$/.exec(filename);
应该这么做。
编辑:在回应PhiLho的评论时,可以这样说:
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;