文件扩展名是文件名末尾的点号(.)后的部分,用于标识文件类型(如.txt、.jpg、.pdf等)。在某些情况下,开发者可能需要在上传文件时删除或修改文件扩展名。
function removeExtension(filename) {
// 方法1: 使用lastIndexOf和substring
const lastDot = filename.lastIndexOf('.');
return lastDot === -1 ? filename : filename.substring(0, lastDot);
// 方法2: 使用正则表达式
// return filename.replace(/\.[^/.]+$/, "");
}
// 使用示例
const originalName = "document.pdf";
const newName = removeExtension(originalName); // "document"
const path = require('path');
function removeExtension(filename) {
return path.parse(filename).name;
}
console.log(removeExtension('image.jpg')); // 输出: image
import os
def remove_extension(filename):
return os.path.splitext(filename)[0]
print(remove_extension("report.docx")) # 输出: report
function removeExtension($filename) {
return pathinfo($filename, PATHINFO_FILENAME);
}
echo removeExtension("presentation.pptx"); // 输出: presentation
public class Main {
public static String removeExtension(String filename) {
int lastDot = filename.lastIndexOf('.');
return lastDot == -1 ? filename : filename.substring(0, lastDot);
}
public static void main(String[] args) {
System.out.println(removeExtension("data.json")); // 输出: data
}
}
如果目的是安全而非美观,可以考虑:
问题1:删除扩展名后无法识别文件类型
问题2:文件名本身包含点号(如"my.file.txt")
问题3:某些操作系统依赖扩展名