js实现queryparams
获取 URL 查询参数(QueryParams)
方法一:使用 URLSearchParams API
现代浏览器支持 URLSearchParams 接口,可直接解析查询字符串:
const urlParams = new URLSearchParams(window.location.search);
const paramValue = urlParams.get('key');
方法二:手动解析查询字符串
适用于不支持 URLSearchParams 的环境:
function getQueryParam(key) {
const params = {};
window.location.search.slice(1).split('&').forEach(pair => {
const [k, v] = pair.split('=');
params[k] = decodeURIComponent(v || '');
});
return params[key];
}
修改或添加查询参数
更新参数并跳转
通过 URLSearchParams 修改后生成新 URL:
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('page', '2');
window.location.search = urlParams.toString();
保留历史记录(不刷新)
使用 history.pushState 更新 URL 而不刷新页面:
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('sort', 'desc');
const newUrl = `${window.location.pathname}?${urlParams.toString()}`;
history.pushState({}, '', newUrl);
删除查询参数
移除单个参数
通过 URLSearchParams.delete() 实现:

const urlParams = new URLSearchParams(window.location.search);
urlParams.delete('filter');
window.location.search = urlParams.toString();
注意事项
- 参数值需用
encodeURIComponent编码,避免特殊字符(如&,=)破坏结构 URLSearchParams不兼容 IE,需 polyfill 或降级方案- 修改
window.location.search会触发页面刷新






