看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
看代码:
var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc
function getFileExtension(filename) {
/*TODO*/
}
当前回答
我更喜欢使用lodash的大多数事情,所以这里有一个解决方案:
function getExtensionFromFilename(filename) {
let extension = '';
if (filename > '') {
let parts = _.split(filename, '.');
if (parts.length >= 2) {
extension = _.last(parts);
}
return extension;
}
其他回答
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
我刚刚意识到,对p4bl0的回答发表评论是不够的,尽管Tom的回答显然解决了问题:
return filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
var extension = fileName.substring(fileName.lastIndexOf('.')+1);
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");
}
}
在node.js中,这可以通过以下代码实现:
var file1 ="50.xsl";
var path = require('path');
console.log(path.parse(file1).name);