简体   繁体   English

从两个绝对路径构造 JavaScript 中的相对路径

[英]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在上面的示例中,结果将是: 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.这类似于这个问题,但我正在寻找最佳的 JavaScript 解决方案,而不是 Java。

If you're running this on the server with node.js: 如果您在node.js的服务器上运行它:

http://nodejs.org/api/path.html#path_path_relative_from_to 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 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. POSIX版本也不错,如果这是你唯一认为需要支持的版本。

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. 使用URL处理很容易出错,所以我强烈建议使用库来处理所有细节。

URI.js makes this simple: URI.js使这很简单:

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 JS URL API 现在应该在浏览器中处理这个问题: https://developer.mozilla.org/en-US/docs/Web/API/URL/

new URL(url, base)新网址(网址,基础)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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