最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Subtract one absolute path from another in Node.js - Stack Overflow

programmeradmin1浏览0评论

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
  • use substring e.g : var sub = pathTwo.substring(pathOne.length, pathTwo.length); – Mohammad Rahchamani Commented Jan 17, 2016 at 8:45
  • I think pathTwo.repalce(pathOne,'') enough – Darth Commented Jan 17, 2016 at 8:46
  • And what if one of paths is malformed? It will produce an incorrect result, e.g.: '/var/www/example.com/scri' will give us pts/foo/foo.js which can't be right. – Slava Fomin II Commented Jan 17, 2016 at 8:48
Add a comment  | 

2 Answers 2

Reset to default 25

Not 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.

发布评论

评论列表(0)

  1. 暂无评论