How can I get file extensions with JavaScript?

2018-12-31 19:48发布

See code:

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

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

30条回答
看淡一切
2楼-- · 2018-12-31 20:05

If you are looking for a specific extension and know its length, you can use substr:

var file1 = "50.xsl";

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

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

查看更多
栀子花@的思念
3楼-- · 2018-12-31 20:08
function getFileExtension(filename)
{
  var ext = /^.+\.([^.]+)$/.exec(filename);
  return ext == null ? "" : ext[1];
}

Tested with

"a.b"     (=> "b") 
"a"       (=> "") 
".hidden" (=> "") 
""        (=> "") 
null      (=> "")  

Also

"a.b.c.d" (=> "d")
".a.b"    (=> "b")
"a..b"    (=> "b")
查看更多
余生请多指教
4楼-- · 2018-12-31 20:09

A one line solution that will also account for query params and any characters in url.

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

// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 20:09

If you are dealing with web urls, you can use:

function getExt(filename){
    return filename.split('.').pop().split("?")[0].split("#")[0];
}

getExt("logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome") // html

Demo: https://jsfiddle.net/squadjot/q5ard4fj/

查看更多
梦该遗忘
6楼-- · 2018-12-31 20:10
fetchFileExtention(fileName) {
    return fileName.slice((fileName.lastIndexOf(".") - 1 >>> 0) + 2);
}
查看更多
梦寄多情
7楼-- · 2018-12-31 20:12

I just realized that it's not enough to put a comment on p4bl0's answer, though Tom's answer clearly solves the problem:

return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
查看更多
登录 后发表回答