6

How compare dynamically two paths in the same domain and get the relative path between them?

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

And get a return path2 to path3 for example = "../../img/"

2 Answers 2

15

A better way would be to use 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'
Sign up to request clarification or add additional context in comments.

Comments

1

Unfortunately, JavaScript has no native method for doing this. But the path module in node.js has! This code has been taken from the node.js path module source code

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('/');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.