I have two paths in Node.js, e.g.:
var pathOne = '/var/www/example/scripts';
var pathTwo = '/var/www/example/scripts/foo/foo.js';
How do I subtract one path from another in order to obtain a relative path?
subtractPath(pathTwo, pathOne); // => 'foo/foo.js'
Is there a module that does this according to all necessary URL rules or do I better use some simple string manipulations?
I have two paths in Node.js, e.g.:
var pathOne = '/var/www/example.com/scripts';
var pathTwo = '/var/www/example.com/scripts/foo/foo.js';
How do I subtract one path from another in order to obtain a relative path?
subtractPath(pathTwo, pathOne); // => 'foo/foo.js'
Is there a module that does this according to all necessary URL rules or do I better use some simple string manipulations?
Share Improve this question asked Jan 17, 2016 at 8:42 Slava Fomin IISlava Fomin II 28.6k34 gold badges134 silver badges208 bronze badges 3 |2 Answers
Reset to default 25Not sure what you mean by "according to all necessary URL rules", but it seems you should be able to just use path.relative
;
> var pathOne = '/var/www/example.com/scripts';
> var pathTwo = '/var/www/example.com/scripts/foo/foo.js';
> path.relative(pathOne, pathTwo)
'foo/foo.js'
> path.relative(pathTwo, pathOne)
'../..'
You can do that easily with a regex:
var pathOne = /^\/your\/path\//
var pathTwo = '/your/path/appendix'.replace(pathOne, '');
This way you can force it to be at the start of the second path (using ^
) and it won't be erased if it isn't an exact match.
Your example would be:
var pathOne = /^\/var\/www\/example.com\/scripts\//;
var pathTwo = '/var/www/example.com/scripts/foo/foo.js'.replace(pathOne, '');
It should return: foo/foo.js
.
substring
e.g :var sub = pathTwo.substring(pathOne.length, pathTwo.length);
– Mohammad Rahchamani Commented Jan 17, 2016 at 8:45pathTwo.repalce(pathOne,'')
enough – Darth Commented Jan 17, 2016 at 8:46'/var/www/example.com/scri'
will give uspts/foo/foo.js
which can't be right. – Slava Fomin II Commented Jan 17, 2016 at 8:48