How to get file extension from a file name in JavaScript?
如何从JavaScript中的文件名获取文件扩展名?
For examples,
举些例子,
For “file.txt”, I want to get “txt”.
For “file2.multi.ext.fileext”, I want to get “fileext”.
对于“ file.txt”,我想获取“ txt”。
对于“ file2.multi.ext.fileext”,我想获取“ fileext”。
This JavaScript function works well for me.
这个JavaScript函数对我来说效果很好。
function getExt(filename)
{
var idx = filename.lastIndexOf('.');
// handle cases like, .htaccess, filename
return (idx < 1) ? "" : filename.substr(idx + 1);
}
It handles situations that the filename has no extensions like “.htaccess” and “filename”.
它可以处理文件名没有扩展名(如“ .htaccess”和“ filename”)的情况。
Answered by Eric Z Ma.
埃里克·马(Eric Z Ma)回答。
//This is fine if you know that there will be a nothing but a file name in "fileName"
function getExt(fileName){
return (fileName.lastIndexOf('.') < 1) ? null : fileName.split('.').slice(-1);
}
//this is better for unexpected path data like: "/weird.folder/somefolder"
function getExt(path){
return (path.match(/(?:.+..+[^\/]+$)/ig) != null) ? path.split('.').slice(-1): 'null';
}
翻译自: https://www.systutorials.com/how-to-get-file-extension-in-javascript/