首页 > 解决方案 > 使用路径字符串从另一个文件中查找文件的相对路径

问题描述

我试图找出一种方法来比较两个绝对(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...

我想要一个体面,干净的方式来解决这个问题......

标签: javascriptpath

解决方案


您可以拆分两条路径,然后使用.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"));


推荐阅读