URLSearchParams 构造函数需传入合法查询字符串,new URLSearchParams() 创建空实例;解析当前URL需用 window.location.search 或 new URL(window.location.href).searchParams。

URLSearchParams 构造函数必须传入合法查询字符串
直接用 new URLSearchParams() 不会自动读取当前页面 URL 的查询参数,它默认创建一个空实例。想解析当前地址栏的 query,得先手动提取 window.location.search(注意这个值自带开头的 ?,URLSearchParams 能正确处理带或不带 ? 的字符串)。
常见错误是写成:
const params = new URLSearchParams(); // 空对象,啥也取不到正确做法是:
-
window.location.search直接传入(推荐,最简) - 或用
new URL(window.location.href).searchParams(更健壮,兼容 hash 后带 query 的情况)
get 与 getAll 的行为差异决定是否允许多值
get() 只返回第一个匹配键的值,遇到重复键(如 ?tag=js&tag=html)会忽略后续;getAll() 返回数组,适合多选、标签类场景。别默认用 get() 然后发现漏数据。
示例:
const params = new URLSearchParams("tag=js&tag=html&count=5");
params.get("tag"); // "js"
params.getAll("tag"); // ["js", "html"]
params.get("count"); // "5"(字符串!不是数字)注意:所有值都是字符串类型,需要数字时务必手动 parseInt() 或 Number() 转换。
has / set / append 操作只影响实例,不修改浏览器地址栏
URLSearchParams 实例是独立对象,调用 set()、append()、delete() 都不会触发页面跳转或 URL 更新。要更新地址栏,必须配合 history.pushState() 或 location.search 赋值。
立即学习“前端免费学习笔记(深入)”;
-
set("id", "123"):覆盖同名键(只留一个) -
append("id", "456"):追加新键值对,允许重复 - 最终生成字符串用
toString(),结果不含?,需自行拼接
例如更新 URL:
const params = new URLSearchParams(window.location.search);
params.set("page", "2");
history.pushState(null, "", `?${params.toString()}`);
IE 不支持,移动端 Android 4.4– 和 iOS 9– 需要 polyfill
原生 URLSearchParams 在老环境会报 undefined 或 not a constructor 错误。不能只靠 typeof URLSearchParams !== "undefined" 判断——某些安卓 WebView 实现了但有 bug(比如 getAll() 返回空数组)。
稳妥做法:
- 项目用 webpack/rollup 时,引入
url-search-params-polyfill并全局注入 - 或检测后动态加载:
if (!window.URLSearchParams || !URLSearchParams.prototype.get) { import("url-search-params-polyfill").then(() => { // 继续使用 }); } - 避免在 polyfill 加载前就执行依赖逻辑(比如组件
mounted钩子里立刻读参)
真正容易被忽略的是编码问题:中文或特殊字符在 URL 中本应是 UTF-8 编码,但 URLSearchParams 构造时若传入未解码字符串(比如从 location.search 直接截取又手动处理过),可能导致 %E4%BD%A0 类似乱码无法被正确识别为“你”。始终优先用原生 location.search 初始化,别自己拼 query 字符串再 decode。











