如何从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