如何从Javascript中的文件名字符串中提取扩展名?

2022-08-30 01:10:31

如何在变量中获取文件的文件扩展名?就像我有一个1.txt我需要它的txt部分。


答案 1

适用于以下所有输入的变体:

  • "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

答案 2

我个人更喜欢将字符串拆分,然后只返回最后一个数组元素:).

var fileExt = filename.split('.').pop();

如果文件名中没有,则取回整个字符串。.

例子:

'some_value'                                   => 'some_value'
'.htaccess'                                    => 'htaccess'
'../images/something.cool.jpg'                 => 'jpg'
'http://www.w3schools.com/jsref/jsref_pop.asp' => 'asp'
'http://stackoverflow.com/questions/680929'    => 'com/questions/680929'