Lodash trimStart在Windows系统下额外截断字符的问题排查
问题:Lodash trimStart在Windows系统下截断字符异常
在使用Lodash v4.17.21执行路径修剪操作时,发现trimStart函数在Windows系统下会多截断一个字符,原生substring方法运行正常,macOS等系统无此问题。代码示例:
const process = require('process'); const lodash = require('lodash') var pathDir = "C:/Users/C5317673/repo-caches/cornerstone" var fileName = "C:/Users/C5317673/repo-caches/cornerstone/CIC/models/advancedreturnsmanagement/FollowUpActivityCodes.cds" console.log(lodash.trimStart(fileName, pathDir)) // 返回 IC/models/advancedreturnsmanagement/FollowUpActivityCodes.cds console.log(fileName.substring(pathDir.length + 1)) // 返回 CIC/models/advancedreturnsmanagement/FollowUpActivityCodes.cds
期望结果以CIC开头,但Lodash输出缺失了第一个C。
问题原因
Lodash的trimStart(原trimLeft)并非按完整字符串前缀匹配修剪,而是将第二个参数视为字符集合,逐个移除字符串开头所有包含在该集合中的字符。你的pathDir中包含字符C,在修剪完pathDir的全部字符及后续的/(pathDir中包含/)后,接下来的C会被判定为属于字符集合,因此被额外截断——这就是异常的核心原因。
解决建议
使用Lodash专门的前缀移除方法:改用
trimPrefix(v4.0.0+支持),该方法针对完整前缀字符串进行匹配移除,而非字符集。建议拼接路径分隔符确保只移除目标前缀及后续斜杠:console.log(lodash.trimPrefix(fileName, `${pathDir}/`))保留原生字符串方法:
substring(pathDir.length + 1)逻辑清晰且运行稳定,直接沿用原生实现是可靠选择,避免Lodash方法的功能歧义。使用Node.js内置路径模块:用
path.relative自动处理跨系统路径,无需手动修剪,代码更健壮:const path = require('path'); const pathDir = "C:/Users/C5317673/repo-caches/cornerstone" const fileName = "C:/Users/C5317673/repo-caches/cornerstone/CIC/models/advancedreturnsmanagement/FollowUpActivityCodes.cds" const relativePath = path.relative(pathDir, fileName); console.log(relativePath);
内容的提问来源于stack exchange,提问作者Prabal Rakshit
相关产品推荐
相关产品推荐

