You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比两个文件路径字符串并提取二者的差异部分

实现方案

方法1:纯字符串处理(全环境通用)

直接通过前缀匹配截取路径,无需依赖第三方库或内置模块:

const filePath = "reports/cucumber/7/cucumber/sample/json/login.json"
const reportFolder = "reports/cucumber/7/cucumber/sample"

// 统一补全基准路径末尾的斜杠,避免误匹配前缀相似的路径
const formattedFolder = reportFolder.endsWith('/') ? reportFolder : `${reportFolder}/`;

if (filePath.startsWith(formattedFolder)) {
  // 截取重合前缀后的内容,补全前导斜杠即可
  const targetPath = `/${filePath.slice(formattedFolder.length)}`;
  console.log(targetPath) // 输出 /json/login.json
}

方法2:Node.js 内置path模块实现(鲁棒性更高)

如果是在Node.js环境中,推荐使用内置path模块处理,可自动兼容Windows反斜杠、多重复斜杠、路径大小写差异等边界情况:

const path = require('path');
const filePath = "reports/cucumber/7/cucumber/sample/json/login.json"
const reportFolder = "reports/cucumber/7/cucumber/sample"

// 获取两个路径的相对路径
const relativePath = path.relative(reportFolder, filePath);
// 统一转为正斜杠格式,补全前导斜杠
const targetPath = `/${relativePath.split(path.sep).join('/')}`;
console.log(targetPath) // 输出 /json/login.json

可根据自己的运行环境选择对应的方案,若需要处理路径不匹配的场景,可自行补充异常分支逻辑。

内容的提问来源于stack exchange,提问作者wanderors

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 06:39:01