示例 1:使用 split() 和 pop()
// program to get the file extension
function getFileExtension(filename){
// get file extension
const extension = filename.split('.').pop();
return extension;
}
// passing the filename
const result1 = getFileExtension('module.js');
console.log(result1);
const result2 = getFileExtension('module.txt');
console.log(result2);
输出
js txt
在上面的程序中,使用 split()
方法和 pop() 方法提取文件名扩展名。
- 使用
split()
方法将文件名分割成单独的数组元素。
这里,filename.split('.')
通过分割字符串得到 ["module", "js"]。 - 使用
pop()
方法返回最后一个数组元素,即扩展名。
示例 2:使用 substring() 和 lastIndexOf()
// program to get the file extension
function getFileExtension(filename){
// get file extension
const extension = filename.substring(filename.lastIndexOf('.') + 1, filename.length);
return extension;
}
const result1 = getFileExtension('module.js');
console.log(result1);
const result2 = getFileExtension('test.txt');
console.log(result2);
输出
js txt
在上面的程序中,使用 substring()
方法和 lastIndexOf()
方法提取文件名扩展名。
filename.lastIndexOf('.') + 1
返回文件名中.
的最后位置。
添加了 **1**,因为位置计数从 **0** 开始。filename.length
属性返回 字符串的长度。substring(filename.lastIndexOf('.') + 1, filename.length)
方法返回给定索引之间的字符。例如,'module.js'.substring(8, 10)
返回 js。- 如果文件名中没有
.
,则使用 OR||
运算符返回原始字符串。
另请阅读