javascript - 使用路径字符串从另一个文件中查找文件的相对路径
问题描述
我试图找出一种方法来比较两个绝对(ish!)文件位置并以尽可能最短的方式从一个到另一个返回相对路径。
/*
Example 1:
..\root\folder\subFolder\myCurrent.file
..\root\folder\subFolder\img\myTarget.image
Expected result:
.\img\myTarget.image
Example 2:
..\root\folder\subFolder\myCurrent.file
..\root\folder\otherSubFolder\img\myTarget.image
Expected result:
..\otherSubFolder\img\myTarget.image
Example 3:
..\root\folder\subFolder\myCurrent.file
..\root\folder\subFolder\myTarget.image
Expected result:
myTarget.image
*/
我试图将路径拆分为数组并比较长度和值,但结果完全是一团糟,我什至还没有做到……
const currentFilePath = activepath.split('\\')
const currentDir = currentFilePath[currentFilePath.indexOf(currentFilePath[currentFilePath.length - 2])];
const targetFilePath = file.path.split('\\');
const targetDir = targetFilePath[targetFilePath.indexOf(targetFilePath[targetFilePath.length - 2])];
const currentFileDepth = currentFilePath.length;
// and so on...
我想要一个体面,干净的方式来解决这个问题......
解决方案
您可以拆分两条路径,然后使用.filter()
. .filter()
然后通过再次使用并最终使用来获取与第二条路径的部分相关的独特组件.join('\\')
来创建结果:
const comparePaths = (a, b) => {
const a_parts = a.split('\\');
const b_parts = b.split('\\');
const arr = [...a_parts, ...b_parts];
const diffs = arr.filter(item => arr.indexOf(item) === arr.lastIndexOf(item));
let path_parts = diffs.filter(part => b_parts.includes(part));
const res = ".".repeat(path_parts.length && path_parts.length-1 || 0) +'\\'+ path_parts.join('\\');
return res;
}
console.log(comparePaths("..\\root\\folder\\subFolder\\myCurrent.file",
"..\\root\\folder\\subFolder\\img\\myTarget.image"));
console.log(comparePaths("..\\root\\folder\\subFolder\\myCurrent.file",
"..\\root\\folder\\otherSubFolder\\img\\myTarget.image"));
console.log(comparePaths("..\\foo\\bar\\foobar.js",
"..\\foo\\bar\\foobar.js"));
推荐阅读
- cmake - 无法正确链接 CMakeLists 中的库
- ios - 使用 NEVPNManager 的 IPSec VPN 在睡眠时不会断开连接
- python - 如何在字符串的奇数位置找到元音?
- c# - 条件为真,但它忽略了 Selenium C# 语句
- python - connectedComponentsWithStats 在 python 中导致内存问题
- symfony - Symfony 4 - 使用 multipart/form-data 发送 POST 请求
- c - 合并排序和递归
- elasticsearch - Elasticsearch 多个建议以及更高级的案例,例如在句子中间匹配前缀
- c# - 在列表视图中获取多个相同条目
- c# - C# 中属性的 Lambda 表达式