如何在保留文件扩展名的前提下清理文件名中的非字母数字字符?
文件名清洗:保留扩展名的正则优化方案
需求
- 将文件名中的空格替换为下划线
_ - 仅保留字母、数字字符,移除包括
.在内的所有特殊字符(文件扩展名的.需保留) - 最终保留完整的合法文件扩展名
问题场景
原有处理逻辑会误删扩展名的.,导致格式错误:
var file_name = "6$.6j& Fh*^h�𝓽𝓸gh\as%7 8M/44.#%^s ha︻┻═┳ sd.pdf"; var output = file_name.replace(/ /g,"_").replace(/\W/g, ''); // 当前输出:66j_Fhhghas78M44s_ha_sdpdf // 期望输出:66j_Fhhghas78M44s_ha_sd.pdf
解决方案
通过拆分主文件名与扩展名、分别清洗后拼接的方式实现精准处理:
实现代码
var file_name = "6$.6j& Fh*^h�𝓽𝓸gh\as%7 8M/44.#%^s ha︻┻═┳ sd.pdf"; // 分割最后一个.,分离主文件名和扩展名 const [namePart, extPart] = file_name.split(/\.(?=[^.]+$)/); // 清洗主文件名:空格换下划线,移除所有非字母数字/下划线的字符 const cleanedName = namePart .replace(/ /g, "_") .replace(/[^a-zA-Z0-9_]/g, ""); // 清洗扩展名:仅保留字母数字,过滤特殊字符 const cleanedExt = extPart ? extPart.replace(/[^a-zA-Z0-9]/g, "") : ""; // 拼接最终结果(无扩展名则直接输出清洗后的主文件名) const output = cleanedExt ? `${cleanedName}.${cleanedExt}` : cleanedName; console.log(output); // 输出:66j_Fhhghas78M44s_ha_sd.pdf
关键说明
split(/\.(?=[^.]+$)/):正则匹配最后一个.,确保文件名中间的.不会被分割(比如my.report.v1.pdf会拆分为my.report.v1和pdf)replace(/[^a-zA-Z0-9_]/g, ""):精准保留合法字符,避免误删下划线(已替换空格得到)- 扩展名单独清洗:避免扩展名中混入特殊字符,同时保证主文件名的特殊字符被完全移除
内容的提问来源于stack exchange,提问作者Eriqa Vague
相关产品推荐
相关产品推荐

