url.searchParams
获取表示网址查询参数的 URLSearchParams 对象。该属性是只读的,但它提供的 URLSearchParams 对象可用于改变 URL 实例;要替换 URL 的全部查询参数,请使用 url.search 设置器。有关详细信息,请参阅 URLSearchParams 文档。
¥Gets the URLSearchParams object representing the query parameters of the
URL. This property is read-only but the URLSearchParams object it provides
can be used to mutate the URL instance; to replace the entirety of query
parameters of the URL, use the url.search setter. See
URLSearchParams documentation for details.
当使用 .searchParams 修改 URL 时要小心,因为根据 WHATWG 规范,URLSearchParams 对象使用不同的规则来确定要对哪些字符进行百分比编码。例如,URL 对象不会对 ASCII 波浪号 (~) 字符进行百分比编码,而 URLSearchParams 将始终对其进行编码:
¥Use care when using .searchParams to modify the URL because,
per the WHATWG specification, the URLSearchParams object uses
different rules to determine which characters to percent-encode. For
instance, the URL object will not percent encode the ASCII tilde (~)
character, while URLSearchParams will always encode it:
const myURL = new URL('https://example.org/abc?foo=~bar');
console.log(myURL.search); // prints ?foo=~bar
// Modify the URL via searchParams...
myURL.searchParams.sort();
console.log(myURL.search); // prints ?foo=%7Ebar