3

如何动态比较同一域中的两条路径并获取它们之间的相对路径?

var path2 = "http://site.net/test1/test2/img/1.jpg" // test example
var path3 = "http://site.net/test1/img/1.jpg" // test example

并获得一个返回 path2 到 path3 例如= "../../img/"

4

2 回答 2

12

更好的方法是使用path.relative

const path = require('path');
const path2 = "http://example.com/test1/test2/img/1.jpg";
const path3 = "http://example.com/test1/img/1.jpg";

const relativePath = path.relative(path.dirname(path2),path.dirname(path3));
console.log(relativePath); //'../../img'
于 2018-10-29T08:53:48.773 回答
1

不幸的是,JavaScript 没有执行此操作的本地方法。但是pathnode.js 中的模块有!此代码取自node.js 路径模块源代码

function relative(from, to) {
    function trim(arr) {
      var start = 0;
      for (; start < arr.length; start++) {
        if (arr[start] !== '') break;
      }

      var end = arr.length - 1;
      for (; end >= 0; end--) {
        if (arr[end] !== '') break;
      }

      if (start > end) return [];
      return arr.slice(start, end - start + 1);
    }

    var fromParts = trim(from.split('/'));
    var toParts = trim(to.split('/'));

    var length = Math.min(fromParts.length, toParts.length);
    var samePartsLength = length;
    for (var i = 0; i < length; i++) {
      if (fromParts[i] !== toParts[i]) {
        samePartsLength = i;
        break;
      }
    }

    var outputParts = [];
    for (var i = samePartsLength; i < fromParts.length; i++) {
      outputParts.push('..');
    }

    outputParts = outputParts.concat(toParts.slice(samePartsLength));

    return outputParts.join('/');
}
于 2013-06-23T17:07:45.540 回答