URLSearchParams
Baseline 广泛可用 *
注意:此功能在 Web Workers 中可用。
URLSearchParams 接口定义了用于处理 URL 查询字符串的实用方法。
URLSearchParams 对象是 可迭代的,因此它们可以直接用于 for...of 结构中,以与查询字符串中出现的顺序相同的顺序遍历键/值对,例如,以下两行是等效的:
for (const [key, value] of mySearchParams) {
}
for (const [key, value] of mySearchParams.entries()) {
}
尽管 URLSearchParams 在功能上与 Map 类似,但在迭代时,由于其实现方式,它可能会遇到一些 Map 不会遇到的 陷阱。
构造函数
URLSearchParams()-
返回一个
URLSearchParams对象实例。
实例属性
size只读-
指示搜索参数条目的总数。
实例方法
URLSearchParams[Symbol.iterator]()-
返回一个
iterator,允许按查询字符串中出现的顺序遍历此对象中包含的所有键/值对。 URLSearchParams.append()-
将指定的键/值对作为新的搜索参数附加。
URLSearchParams.delete()-
从所有搜索参数列表中删除名称和可选值匹配的搜索参数。
URLSearchParams.entries()-
返回一个
iterator,允许按查询字符串中出现的顺序遍历此对象中包含的所有键/值对。 URLSearchParams.forEach()-
允许通过回调函数遍历此对象中包含的所有值。
URLSearchParams.get()-
返回与给定搜索参数关联的第一个值。
URLSearchParams.getAll()-
返回与给定搜索参数关联的所有值。
URLSearchParams.has()-
返回一个布尔值,指示给定的参数或参数和值对是否存在。
URLSearchParams.keys()-
返回一个
iterator,允许遍历此对象中包含的键/值对的所有键。 URLSearchParams.set()-
将与给定搜索参数关联的值设置为给定的值。如果存在多个值,则删除其他值。
URLSearchParams.sort()-
按键对所有键/值对(如果有)进行排序。
URLSearchParams.toString()-
返回一个包含适合在 URL 中使用的查询字符串的字符串。
URLSearchParams.values()-
返回一个
iterator,允许遍历此对象中包含的键/值对的所有值。
示例
使用 URLSearchParams
const paramsString = "q=URLUtils.searchParams&topic=api";
const searchParams = new URLSearchParams(paramsString);
// Iterating the search parameters
for (const p of searchParams) {
console.log(p);
}
console.log(searchParams.has("topic")); // true
console.log(searchParams.has("topic", "fish")); // false
console.log(searchParams.get("topic") === "api"); // true
console.log(searchParams.getAll("topic")); // ["api"]
console.log(searchParams.get("foo") === null); // true
console.log(searchParams.append("topic", "webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=api&topic=webdev"
console.log(searchParams.set("topic", "More webdev"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=More+webdev"
console.log(searchParams.delete("topic"));
console.log(searchParams.toString()); // "q=URLUtils.searchParams"
搜索参数也可以是一个对象。
const paramsObj = { foo: "bar", baz: "bar" };
const searchParams = new URLSearchParams(paramsObj);
console.log(searchParams.toString()); // "foo=bar&baz=bar"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // "bar"
解析 window.location
与 URL 不同,Location 接口不提供现成的 searchParams 属性。我们可以使用 URLSearchParams 解析 location.search。
// Assume page has location:
// https://mdn.org.cn/en-US/docs/Web/API/URLSearchParams?foo=a
const paramsString = window.location.search;
const searchParams = new URLSearchParams(paramsString);
console.log(searchParams.get("foo")); // a
重复的搜索参数
const paramStr = "foo=bar&foo=baz";
const searchParams = new URLSearchParams(paramStr);
console.log(searchParams.toString()); // "foo=bar&foo=baz"
console.log(searchParams.has("foo")); // true
console.log(searchParams.get("foo")); // bar, only returns the first value
console.log(searchParams.getAll("foo")); // ["bar", "baz"]
无 URL 解析
URLSearchParams 构造函数不解析完整的 URL。但是,如果存在,它会剥离字符串开头的 ?。
const paramsString1 = "http://example.com/search?query=%40";
const searchParams1 = new URLSearchParams(paramsString1);
console.log(searchParams1.has("query")); // false
console.log(searchParams1.has("http://example.com/search?query")); // true
console.log(searchParams1.get("query")); // null
console.log(searchParams1.get("http://example.com/search?query")); // "@" (equivalent to decodeURIComponent('%40'))
const paramsString2 = "?query=value";
const searchParams2 = new URLSearchParams(paramsString2);
console.log(searchParams2.has("query")); // true
const url = new URL("http://example.com/search?query=%40");
const searchParams3 = new URLSearchParams(url.search);
console.log(searchParams3.has("query")); // true
百分比编码
URLSearchParams 对象会 对 application/x-www-form-urlencoded 的百分比编码集(包含除 ASCII 字母数字、*、-、. 和 _ 之外的所有码点)中的任何内容进行百分比编码,并将 U+0020 空格编码为 +。但是,它仅在序列化和反序列化完整的 URL 搜索参数语法时处理百分比编码。在与单个键和值交互时,您始终使用未编码的版本。
// Creation from parsing a string: percent-encoding is decoded
const params = new URLSearchParams("%24%25%26=%28%29%2B");
// Retrieving all keys/values: only decoded values are returned
console.log([...params]); // [["$%&", "()+"]]
// Getting an individual value: use the decoded key and get the decoded value
console.log(params.get("$%&")); // "()+"
console.log(params.get("%24%25%26")); // null
// Setting an individual value: use the unencoded key and value
params.append("$%&$#@+", "$#&*@#()+");
// Serializing: percent-encoding is applied
console.log(params.toString());
// "%24%25%26=%28%29%2B&%24%25%26%24%23%40%2B=%24%23%26*%40%23%28%29%2B"
如果附加一个带有百分比编码键的键/值对,该键将被视为未编码并再次进行编码。
const params = new URLSearchParams();
params.append("%24%26", "value");
params.toString(); // "%2524%2526=value"
保留加号
URLSearchParams 构造函数将加号 (+) 解释为空格,这可能会导致问题。在下面的示例中,我们使用 十六进制转义序列 来模拟包含二进制数据(其中每个字节都包含信息)的字符串,该字符串需要存储在 URL 搜索参数中。请注意 btoa() 生成的编码字符串包含 +,但 URLSearchParams 未保留它。
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'
const searchParams = new URLSearchParams(`bin=${base64Data}`); // 'bin=E+AXQB+A'
const binQuery = searchParams.get("bin"); // 'E AXQB A', '+' is replaced by spaces
console.log(atob(binQuery) === rawData); // false
切勿使用动态插值字符串构建 URLSearchParams 对象。而是使用 append() 方法,如上所述,该方法将所有字符按原样解释。
const rawData = "\x13à\x17@\x1F\x80";
const base64Data = btoa(rawData); // 'E+AXQB+A'
const searchParams = new URLSearchParams();
searchParams.append("bin", base64Data); // 'bin=E%2BAXQB%2BA'
const binQuery = searchParams.get("bin"); // 'E+AXQB+A'
console.log(atob(binQuery) === rawData); // true
与 URL.searchParams 的交互
URL.searchParams 属性将 URL 的 search 字符串公开为 URLSearchParams 对象。更新此 URLSearchParams 时,URL 的 search 会随其序列化而更新。但是,URL.search 编码的字符子集与 URLSearchParams 不同,并且将空格编码为 %20 而不是 +。这可能会导致一些意外的交互——如果您更新 searchParams,即使值相同,URL 的序列化方式也可能不同。
const url = new URL("https://example.com/?a=b ~");
console.log(url.href); // "https://example.com/?a=b%20~"
console.log(url.searchParams.toString()); // "a=b+%7E"
// This should be a no-op, but it changes the URL's query to the
// serialization of its searchParams
url.searchParams.sort();
console.log(url.href); // "https://example.com/?a=b+%7E"
const url2 = new URL("https://example.com?search=1234¶m=my%20param");
console.log(url2.search); // "?search=1234¶m=my%20param"
url2.searchParams.delete("search");
console.log(url2.search); // "?param=my+param"
空值与无值
URLSearchParams 不区分没有 = 之后内容的参数与根本没有 = 的参数。
const emptyVal = new URLSearchParams("foo=&bar=baz");
console.log(emptyVal.get("foo")); // returns ''
const noEquals = new URLSearchParams("foo&bar=baz");
console.log(noEquals.get("foo")); // also returns ''
console.log(noEquals.toString()); // 'foo=&bar=baz'
规范
| 规范 |
|---|
| URL # urlsearchparams |
浏览器兼容性
加载中…