前端修改URL路径时如何保留原有查询参数?
修改页面路径保留查询参数的实现方法
你直接赋值/new_path丢失参数的原因是该写法仅传入了纯路径,没有携带原有地址的查询参数部分,可通过以下两种方式实现需求:
方案1:使用URL API(推荐,现代浏览器通用)
该方法无需手动处理参数拼接,会自动保留所有查询参数、哈希锚点,出错概率低:
// 基于当前页面地址初始化URL对象 const currentUrl = new URL(window.location.href); // 仅修改路径部分 currentUrl.pathname = '/new_path'; // 执行跳转 window.location.href = currentUrl.href;
方案2:手动拼接(兼容低版本浏览器)
如果需要兼容不支持URL API的旧浏览器,可以直接提取原生属性拼接:
// window.location.search 为?开头的完整查询参数,window.location.hash为#开头的锚点 window.location.href = '/new_path' + window.location.search + window.location.hash;
内容的提问来源于stack exchange,提问作者Fllappy
相关产品推荐
相关产品推荐

