如何从Javascript中的文件名字符串中提取扩展名? [英] How to extract extension from filename string in Javascript?
本文介绍了如何从Javascript中的文件名字符串中提取扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在变量中获取文件的File扩展名?
就好像我有一个文件 1.txt 我需要 txt 部分。
how would i get the File extension of the file in a variable? like if I have a file as 1.txt I need the txt part of it.
推荐答案
适用于以下所有输入的变体:
A variant that works with all of the following inputs:
-
file.name.with.dots.txt
-
file.txt
-
file
-
-
null
-
undefined
"file.name.with.dots.txt"
"file.txt"
"file"
""
null
undefined
将是:
var re = /(?:\.([^.]+))?$/;
var ext = re.exec("file.name.with.dots.txt")[1]; // "txt"
var ext = re.exec("file.txt")[1]; // "txt"
var ext = re.exec("file")[1]; // undefined
var ext = re.exec("")[1]; // undefined
var ext = re.exec(null)[1]; // undefined
var ext = re.exec(undefined)[1]; // undefined
解释
(?: # begin non-capturing group
\. # a dot
( # begin capturing group (captures the actual extension)
[^.]+ # anything except a dot, multiple times
) # end capturing group
)? # end non-capturing group, make it optional
$ # anchor to the end of the string
这篇关于如何从Javascript中的文件名字符串中提取扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文