5

Given two absolute paths, e.g.

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

3
  • 2
    use URI.js. Commented Dec 5, 2012 at 20:13
  • What do you mean by "optimal"? Optimal in code size, running time or memory usage? Commented Dec 5, 2012 at 20:15
  • code size. can't imagine memory usage or running time will be a considerable factor for something so trivial. Commented Dec 5, 2012 at 20:24

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm running client side, but that looks workable. Will see if I can get it working.
1

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');

4 Comments

Looks like it would work but is there a more concise way than including a whole library?
Probably, but how close are you monitoring your performance to care?
@AdamJimenez, that's not an answer. You should be making your site work first and then testing with a performance optimizer to see where the greatest gains can be made in performance. Prematurely optimizing is only going to hold you back.
URI.js github page now recommends using JS URL API: developer.mozilla.org/en-US/docs/Web/API/URL
-1

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/'

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.