示例 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) || filename; 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 || 运算符用于在文件名中没有 . 时返回原始字符串。

