简体   繁体   中英

Construct a relative path in JavaScript from two absolute paths

Given two absolute paths, eg

/var/data/stuff/xyz.html
/var/data

How to create a relative path that uses the second path as its base? In the example above, the result would be: stuff/xyz.html

Another example:

/relative/sub/foo/sub/file
/relative/path
../../../path 

This is similar to this question but I'm looking for the optimal JavaScript solution instead of Java.

If you're running this on the server with node.js:

http://nodejs.org/api/path.html#path_path_relative_from_to

This is their implementation:

https://github.com/joyent/node/blob/master/lib/path.js#L233

This should work in the browser without really any changes. It's been battle-tested, so it already handles edge cases. It's not a one-liner, but it works flawlessly, which I think is more important. The POSIX version isn't bad, if that's the only think you need to support.

It's really easy to make mistakes with URL handling, so I highly recommend using a library to take care of all the nitty gritty details.

URI.js makes this simple:

URI('/var/data/stuff/xyz.html').relativeTo('/var/data');

JS URL API should handle this within the browser now: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL

new URL(url, base)

// Base urls
let m = 'https://developer.mozilla.org';
let a = new URL("/", m);                                // => 'https://developer.mozilla.org/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM