如何使用JavaScript获取文件扩展名? [英] How can I get file extensions with JavaScript?

查看:139
本文介绍了如何使用JavaScript获取文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参见代码:

var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExtension(filename) {
    /*TODO*/
}


推荐答案

更新编辑:自从这个问题最初发布以来,很多事情都发生了变化 - 有很多非常好的信息在 wallacer的修订答案以及 VisioN的优秀分类

Newer Lots of things have changed since this question was initially posted - there's a lot of really good information in wallacer's revised answer as well as VisioN's excellent breakdown

编辑:因为这是接受的答案; wallacer的回答确实要好得多:

Just because this is the accepted answer; wallacer's answer is indeed much better:

return filename.split('.').pop();






我的回答是:


My old answer:

return /[^.]+$/.exec(filename);

应该这样做。

编辑:为了回应PhiLho的评论,请使用以下内容:

In response to PhiLho's comment, use something like:

return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;

这篇关于如何使用JavaScript获取文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆