看代码:

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

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

当前回答

如果你正在寻找一个特定的扩展名,并且知道它的长度,你可以使用substr:

var file1 = "50.xsl";

if (file1.substr(-4) == '.xsl') {
  // do something
}

JavaScript参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

其他回答

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");
  }
}

// 获取文件后缀名 function getFileExtension(file) { var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i; var extension = file.match(regexp); return extension && extension[1]; } console.log(getFileExtension("https://www.example.com:8080/path/name/foo")); console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR")); console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment")); console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));

快速和正确的路径工作

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

一些边缘情况

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

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

更新编辑:自从这个问题最初发布以来,很多事情都发生了变化——wallacer修改后的答案中有很多非常好的信息,VisioN也有很好的细分


编辑:因为这是公认的答案;Wallacer的回答确实好得多:

return filename.split('.').pop();

我以前的回答是:

return /[^.]+$/.exec(filename);

应该这么做。

编辑:在回应PhiLho的评论时,可以这样说:

return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;

我知道这是一个老问题,但我写了这个函数的测试提取文件扩展名,她可用的NPM, Yarn, Bit。 也许它会帮助别人。 https://bit.dev/joshk/jotils/get-file-extension

function getFileExtension(path: string): string {
    var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i
    var extension = path.match(regexp)
    return extension && extension[1]
}

您可以在这里看到我编写的测试。