URLSearchParams:URLSearchParams() 构造函数
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
备注: 此特性在 Web Worker 中可用。
URLSearchParams()
构造函数创建并返回一个新的 URLSearchParams
对象。
语法
js
new URLSearchParams()
new URLSearchParams(options)
参数
返回值
一个 URLSearchParams
实例。
示例
下面的例子展示了用各种传入的参数来创建一个 URLSearchParams
对象。
js
// 通过 url.search 检索参数,传递到构造函数
const url = new URL("https://example.com?foo=1&bar=2");
const params1 = new URLSearchParams(url.search);
// 直接从 URL 对象获取 URLSearchParams 对象
const params1a = url.searchParams;
// 传入字符串
const params2 = new URLSearchParams("foo=1&bar=2");
const params2a = new URLSearchParams("?foo=1&bar=2");
// 传入一系列键值对
const params3 = new URLSearchParams([
["foo", "1"],
["bar", "2"],
]);
// 传入记录
const params4 = new URLSearchParams({ foo: "1", bar: "2" });
这个示例展示了如何使用来自一个带有查询参数的 URL 构建的查询参数对象创建一个新的 URL。
js
const url = new URL("https://example.com/?a=hello&b=world");
console.log(url.href);
// https://example.com/?a=hello&b=world
console.log(url.origin);
// https://example.com
const add_params = {
c: "a",
d: new String(2),
e: false.toString(),
};
const new_params = new URLSearchParams([
...Array.from(url.searchParams.entries()), // [["a","hello"],["b","world"]]
...Object.entries(add_params), // [["c","a"],["d","2"],["e","false"]]
]).toString();
console.log(new_params);
// a=hello&b=world&c=a&d=2&e=false
const new_url = new URL(`${url.origin}${url.pathname}?${new_params}`);
console.log(new_url.href);
// https://example.com/?a=hello&b=world&c=a&d=2&e=false
// 在这里,它是一个接受 (URL, Record<string, string>) 的函数
const addSearchParams = (url, params = {}) =>
new URL(
`${url.origin}${url.pathname}?${new URLSearchParams([
...Array.from(url.searchParams.entries()),
...Object.entries(params),
])}`,
);
规范
Specification |
---|
URL Standard # dom-urlsearchparams-urlsearchparams |
浏览器兼容性
BCD tables only load in the browser