解析到 URL 的相对引用

可以使用 URL() 构造函数URL APIURL.parse() 静态方法,将相对引用和基础 URL 解析为绝对 URL。

这两种方法最多接受两个字符串参数,并返回一个表示绝对 URL 的 URL() 对象。第一个参数表示绝对 URL 或 URL 的相对引用,第二个参数是基础 URL,用于在第一个参数指定了相对引用时解析它。这两种方法解析相对引用的方式相同,不同之处在于,如果传入了无效 URL,URL() 构造函数会抛出错误,而 parse() 则返回 null

下面的代码显示了如何使用相同的 urlbase URL 值来调用这些方法。

js
const url = "articles";
const base = "https://mdn.org.cn/some/path";
const constructorResult = new URL(url, base);
// => https://mdn.org.cn/some/articles
const parseResult = URL.parse(url, base);
// => https://mdn.org.cn/some/articles

从示例中可以看出,从提供的基础 URL 和相对引用解析 URL 并不是简单地将提供的参数串联起来。

在这种情况下,传入了一个相对于当前目录的路径(articles)。base URL 的当前目录是 URL 字符串中最后一个正斜杠之前的部分。这里 https://mdn.org.cn/some/path 没有尾随正斜杠,因此当前目录是 https://mdn.org.cn/some/,最终解析的 URL 是 https://mdn.org.cn/some/articles

相对引用是相对于以下内容的路径引用,并根据基础 URL 进行解析:当前目录 (./)、当前目录的父目录 (../) 或站点根目录 (/)。接下来的部分将展示每种相对路径的解析方式。

当前目录相对

./ 或没有前缀(例如 ./articlearticle./article/)开头的相对引用,是相对于 base 参数表示的 URL 的当前目录。

base URL 的当前目录是 URL 字符串中最后一个正斜杠之前的部分,对于下面代码块中的两个 base 字符串,这都是 https://test.example.org/api/。将当前目录相对引用 article 附加到此,解析为 https://test.example.org/api/article

js
log(new URL("./article", "https://test.example.org/api/").href);
// => https://test.example.org/api/article
log(new URL("article", "https://test.example.org/api/v1").href);
// => https://test.example.org/api/article

类似地,在下面的两个基础 URL 字符串中,当前目录都是 https://test.example.org/api/v2/。我们将 story/story 附加到这些 URL 上,以解析最终的 URL。

js
log(new URL("./story/", "https://test.example.org/api/v2/").href);
// => https://test.example.org/api/v2/story/
log(new URL("./story", "https://test.example.org/api/v2/v3").href);
// => https://test.example.org/api/v2/story

父目录相对

../ 开头的相对引用(例如 ../path)是相对于 base 参数表示的 URL 的当前目录的父目录。每出现一次 ../,就会从当前目录中移除一个文件夹,然后 ../ 后面的任何文本都会附加到剩余的基础路径上。您可以通过多次指定 ../ 来向上导航到父目录,但最多只能导航到站点根目录的级别。

例如,给定基础 URL https://test.example.com/test/api/v1/ 和一个父目录相对 URL ../some/path,当前目录是 https://test.example.com/test/api/v1/,父目录是 https://test.example.com/test/api/,解析后的绝对 URL 是 https://test.example.com/test/api/some/path

以下示例将更详细地说明这一点。在所有情况下,当前目录都是 https://test.example.org/api/v1/v2/(在第二种情况下,v3 在最后一个正斜杠之后),每个相对引用都会解析到不同的父目录。

js
log(new URL("../path", "https://test.example.org/api/v1/v2/").href);
// => https://test.example.org/api/v1/path
log(new URL("../../path", "https://test.example.org/api/v1/v2/v3").href);
// => https://test.example.org/api/path
log(new URL("../../../../path", "https://test.example.org/api/v1/v2/").href);
// => https://test.example.org/path

根目录相对

/ 开头的相对引用(例如 /path)是相对于 base 参数指定的 URL 的站点根目录。例如,给定基础 URL https://test.example.com/api/v1,根目录相对 URL /some/path 的解析 URL 是 https://test.example.com/some/path

注意: 在解析根目录相对 URL 时,base URL 的路径部分无关紧要。

以下是一些更多示例。

js
log(new URL("/some/path", "https://test.example.org/api/").href);
// => https://test.example.org/some/path
log(new URL("/", "https://test.example.org/api/v1/").href);
// => https://test.example.org/
log(new URL("/article", "https://example.com/api/v1/").href);
// => https://example.com/article

另见