3

js获取文件名后缀

 1 year ago
source link: https://www.fly63.com/article/detial/11381
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
更新日期: 2022-04-25阅读量: 205标签: 文件分享

扫一扫分享

有时候我们需要通过文件名或者路径,得到该文件的后缀名(扩展名),可以通过如下几种方式进行截取。例如文件名为:

var name="https://www.fly63.com/file/1024.txt";

方式一:subtring() 

使用subtring() 截取字符串,对于文件名中会出现多个点的很有用,从最后一个点的地方截取。

var suffix = name.substring(name.lastIndexOf("."));//.txt
/*只获取后缀*/
var suffix =name.substring(name.lastIndexOf(".")+1);//txt

方式二:正则

使用正则,对只会出现一个点的适用:

var suffix = name.match(/.[^.]+$/)[0];//.txt
/*只获取后缀*/
var suffix = name.match(/[^.]+$/)[0];//txt

方式三:转数组

var suffix = '.'+name.split('.').pop();//.txt

方式四:substr()

同subtring()的字符串截取

var suffix = name.substr(name.lastIndexOf("."));//'.txt'
var suffix = name.substr(name.lastIndexOf(".")+1);//txt

链接: https://www.fly63.com/article/detial/11381


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK