如果您愿意使用 JQuery,您可能会考虑一起跳过正则表达式并使用一组有效扩展名来代替:
// store the file extensions (easy to maintain, if changesa are needed)
var aValidExtensions = ["htm", "html", "class", "js"];
// split the filename on "."
var aFileNameParts = file_name.split(".");
// if there are at least two pieces to the file name, continue the check
if (aFileNameParts.length > 1) {
// get the extension (i.e., the last "piece" of the file name)
var sExtension = aFileNameParts[aFileNameParts.length-1];
// if the extension is in the array, return true, if not, return false
return ($.inArray(sExtension, aValidExtensions) >= 0) ? true : false;
}
else {
return false; // invalid file name format (no file extension)
}
这里最大的优势在于易于维护。. . 更改可接受的文件扩展名是对数组的快速更新(甚至是属性或 CMS 更新,具体取决于事物的花哨:))。此外,regex
有一个有点过程密集的习惯,所以这应该更有效(虽然,我还没有测试过这个特殊情况)。