看代码:
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*/
}
当前回答
var extension = fileName.substring(fileName.lastIndexOf('.')+1);
其他回答
在node.js中,这可以通过以下代码实现:
var file1 ="50.xsl";
var path = require('path');
console.log(path.parse(file1).name);
一行解决方案,也将考虑查询参数和url中的任何字符。
string.match(/(.*)\??/i).shift().replace(/\?.*/, '').split('.').pop()
// Example
// some.url.com/with.in/&ot.s/files/file.jpg?spec=1&.ext=jpg
// jpg
如果你正在处理web url,你可以使用:
function getExt(filepath){
return filepath.split("?")[0].split("#")[0].split('.').pop();
}
getExt("../js/logic.v2.min.js") // js
getExt("http://example.net/site/page.php?id=16548") // php
getExt("http://example.net/site/page.html#welcome.to.me") // html
getExt("c:\\logs\\yesterday.log"); // log
演示:https://jsfiddle.net/squadjot/q5ard4fj/
还有一个使用ES6解构的简单方法:
Const path = 'hello.world.txt' const[扩展,…nameParts] = path.split('.').reverse(); console.log(扩展:,扩展);
Wallacer的回答很好,但还需要再检查一下。
如果文件没有扩展名,它将使用filename作为扩展名,这是不好的。
试试这个:
return ( filename.indexOf('.') > 0 ) ? filename.split('.').pop().toLowerCase() : 'undefined';