WHATWG API


WHATWG URL 标准 在选择编码字符时采用的方式比传统 API 更有选择性且更精细。

【The WHATWG URL Standard uses a more selective and fine grained approach to selecting encoded characters than that used by the Legacy API.】

WHATWG 算法定义了四个“百分比编码集”,用于描述必须进行百分比编码的字符范围:

【The WHATWG algorithm defines four "percent-encode sets" that describe ranges of characters that must be percent-encoded:】

  • C0 控制百分号编码集合 包括范围从 U+0000 到 U+001F(含)以及所有大于 U+007E (~) 的代码点。
  • 片段百分比编码集合 包括 C0 控制百分比编码集合 以及代码点 U+0020 空格、U+0022 (")、U+003C (<), U+003E (>) 和 U+0060 (`)。
  • 路径百分号编码集合 包括 C0 控制百分号编码集合 以及代码点 U+0020 空格、U+0022 (")、U+0023 (#)、U+003C (<), U+003E (>)、U+003F (?)、U+0060 (`)、U+007B ({) 和 U+007D (})。
  • userinfo 编码集 包括 path 百分比编码集 以及码点 U+002F (/)、U+003A (:)、U+003B (;)、U+003D (=)、U+0040 (@)、U+005B ([) 到 U+005E (^) 和 U+007C (|)。

userinfo 百分号编码集 专门用于 URL 中编码的用户名和密码。path 百分号编码集 用于大多数 URL 的路径。fragment 百分号编码集 用于 URL 的片段。C0 控制百分号编码集 在某些特定情况下用于主机和路径,除此之外还用于所有其他情况。

【The userinfo percent-encode set is used exclusively for username and passwords encoded within the URL. The path percent-encode set is used for the path of most URLs. The fragment percent-encode set is used for URL fragments. The C0 control percent-encode set is used for host and path under certain specific conditions, in addition to all other cases.】

当主机名中出现非 ASCII 字符时,主机名会使用 Punycode 算法进行编码。但是,请注意,主机名可能同时包含 Punycode 编码和百分号编码的字符:

【When non-ASCII characters appear within a host name, the host name is encoded using the Punycode algorithm. Note, however, that a host name may contain both Punycode encoded and percent-encoded characters:】

const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.example.com/foo
console.log(myURL.origin);
// Prints https://xn--1xa.example.com