学完这篇,你能用浏览器内置的 URL 和 URLSearchParams 把地址拆开、改参数、再拼回去,不再手写字符串拼接和 encodeURIComponent。
第一步:用 URL 构造函数把地址拆成零件
过去解析 URL 要写正则,现在一行就够。new URL() 接受一个完整地址,返回一个带属性的对象:
const url = new URL('https://example.com:8080/post/123?tab=reply&page=2#comment-5');
url.protocol // 'https:'
url.hostname // 'example.com'
url.port // '8080'
url.pathname // '/post/123'
url.search // '?tab=reply&page=2'
url.hash // '#comment-5'
url.origin // 'https://example.com:8080'
几个容易记混的点:host 包含端口,hostname 不包含;search 带问号,hash 带井号;origin 是协议+域名+端口,不含路径。
注意:传入不完整的地址(比如 /post/123)会直接抛 TypeError: Invalid URL。这种情况必须给第二个参数当基准地址,见第三步。
第二步:用 URLSearchParams 读写查询参数
拿 url.searchParams 就能像操作 Map 一样操作参数:
const params = new URLSearchParams('?tab=reply&page=2&tag=js&tag=web');
params.get('tab'); // 'reply'
params.has('page'); // true
params.getAll('tag'); // ['js', 'web']
params.set('page', 3); // 有则改,无则加
params.append('tag', 'css'); // 追加,不覆盖同名的
params.delete('tab'); // 删除
params.toString(); // 'page=3&tag=js&tag=web&tag=css'
get 只返回第一个同名值,要拿全部得用 getAll,这是处理多选筛选条件时最常见的坑。
注意:url.searchParams 是“活”的,改它会直接改到 url 上,不用手动回写 url.search。改完读 url.href 或 url.toString() 就是最终地址。
第三步:处理相对路径和当前页面
new URL(相对路径, 基准地址) 会自动做路径合并:
new URL('/post/1', 'https://example.com/bbs/'); // https://example.com/post/1
new URL('post/1', 'https://example.com/bbs/'); // https://example.com/bbs/post/1
开头的斜杠决定是“从根开始”还是“相对当前目录”。想基于当前页面改参数,直接用 location.href 当基准:
const url = new URL(location.href);
url.searchParams.set('page', 3);
url.hash = ''; // 切页时清掉锚点
history.pushState({}, '', url); // 地址栏变了但不刷新
这段代码适合做列表分页、筛选条件切换,比 location.href = ... 体验好得多。
第四步:几种高频实战写法
清空所有参数,只留路径:
url.search = '';
只保留白名单参数(防止别人塞垃圾参数):
const keep = ['page', 'sort'];
[...url.searchParams.keys()].forEach(k => {
if (!keep.includes(k)) url.searchParams.delete(k);
});
参数里有中文或特殊字符: 不用手动编码,set / append 会自动处理:
const u = new URL('https://example.com/s');
u.searchParams.set('q', '中文 & 符号');
u.search; // '?q=%E4%B8%AD%E6%96%87+%26+%E7%AC%A6%E5%8F%B7'
注意:解码时 + 会被当成空格。如果你的参数值本身含加号(比如 base64),别用 URLSearchParams 直接解,先用 decodeURIComponent 处理,或者传值时用 set 让它编码成 %2B。
hash 里藏参数的情况(很多单页应用这么干):
const hashParams = new URLSearchParams(url.hash.slice(1));
// 改完再塞回去
url.hash = '#' + hashParams.toString();
注意:# 后面的内容不会发送到服务器,别把需要后端读取的参数放 hash 里。
小结
- 拆地址用
new URL(地址),取 protocol / hostname / port / pathname / search / hash / origin。
- 改参数用
url.searchParams 的 get / getAll / set / append / delete,改完读 url.href。
set 覆盖同名、append 追加同名、get 只拿第一个,多值筛选必须用 getAll。
- 相对路径要给
new URL() 传第二个基准地址,否则报错。
- 编码交给 API 自动做,别手拼字符串;注意
+ 在解码时会被当作空格。