URLSearchParams:get() 方法

Baseline 已广泛支持

此功能已成熟,可跨多种设备和浏览器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有浏览器中可用。

注意:此功能在 Web Workers 中可用。

URLSearchParams 接口的 get() 方法返回与给定搜索参数关联的第一个值。

语法

js
get(name)

参数

name

要返回的参数名称。

返回值

如果找到给定的搜索参数,则返回一个字符串;否则返回 null

示例

如果你的页面的 URL 是 https://example.com/?name=Jonathan&age=18,你可以使用以下方法解析出 'name' 和 'age' 参数:

js
let params = new URLSearchParams(document.location.search);
let name = params.get("name"); // is the string "Jonathan"
let age = parseInt(params.get("age"), 10); // is the number 18

请求查询字符串中不存在的参数将返回 null

js
let address = params.get("address"); // null

规范

规范
URL
# dom-urlsearchparams-get

浏览器兼容性