看代码:

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

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

当前回答

在path模块中有一个标准库函数:

import path from 'path';

console.log(path.extname('abc.txt'));

输出:

. txt

所以,如果你只想要格式:

path.extname('abc.txt').slice(1) // 'txt'

如果没有扩展名,函数将返回一个空字符串:

path.extname('abc') // ''

如果使用Node,则path是内置的。如果你的目标是浏览器,那么Webpack将为你捆绑一个路径实现。如果你的目标浏览器没有Webpack,那么你可以手动包含path-browserify。

没有理由进行字符串分割或正则表达式。

其他回答

function func() {
  var val = document.frm.filename.value;
  var arr = val.split(".");
  alert(arr[arr.length - 1]);
  var arr1 = val.split("\\");
  alert(arr1[arr1.length - 2]);
  if (arr[1] == "gif" || arr[1] == "bmp" || arr[1] == "jpeg") {
    alert("this is an image file ");
  } else {
    alert("this is not an image file");
  }
}

一行解决方案,也将考虑查询参数和url中的任何字符。

string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()

// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
var file = "hello.txt";
var ext = (function(file, lio) { 
  return lio === -1 ? undefined : file.substring(lio+1); 
})(file, file.lastIndexOf("."));

// hello.txt -> txt
// hello.dolly.txt -> txt
// hello -> undefined
// .hello -> hello

快速和正确的路径工作

(filename.match(/[^\\\/]\.([^.\\\/]+)$/) || [null]).pop()

一些边缘情况

/path/.htaccess => null
/dir.with.dot/file => null

使用split的解决方案很慢,使用lastIndexOf的解决方案不能处理边缘情况。

使用reduce和数组解构来获取文件名和扩展名:

Var STR = "filename.with_dot.png"; Var [filename, extension] = str.split('.')。Reduce ((acc, val, i, arr) => (i == arr。长度- 1)?(acc [0] .substring (1), val]: [[acc [0], val] . join ('.')], []) console.log({文件名,扩展});

有更好的缩进:

var str = "filename.with_dot.png";
var [filename, extension] = str.split('.')
   .reduce((acc, val, i, arr) => (i == arr.length - 1) 
       ? [acc[0].substring(1), val] 
       : [[acc[0], val].join('.')], [])


console.log({filename, extension});

// {
//   "filename": "filename.with_dot",
//   "extension": "png"
// }