You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery在URL最后一个斜杠后添加内容(兼容查询字符串)

解决方案:用原生URL API轻松处理URL拼接问题

这问题我之前也碰到过,手动拆分字符串处理URL很容易踩各种坑(比如结尾斜杠、查询字符串有无的情况),用浏览器原生的URL API来处理就稳多了,它能自动帮我们解析URL的各个组成部分,不用自己写一堆判断逻辑。

下面是具体的实现代码,我分步骤给你解释:

步骤1:解析当前URL

首先用URL对象解析当前页面的URL,它会自动把URL拆分成origin(协议+域名+端口)、pathname(路径部分)、search(查询字符串,包含?)等部分:

// 获取当前页面URL并解析
const currentUrl = new URL(window.location.href);
// 要添加到路径末尾的内容,比如这里的'sale'
const appendStr = 'sale';

步骤2:处理路径部分

接下来处理路径,不管原路径结尾有没有斜杠,我们都能正确把内容加到最后一个斜杠之后:

let updatedPath = currentUrl.pathname;
// 如果路径以斜杠结尾,先去掉末尾的斜杠
if (updatedPath.endsWith('/')) {
  updatedPath = updatedPath.slice(0, -1);
}
// 拼接上要添加的内容
updatedPath += `/${appendStr}`;

步骤3:组合新URL并使用

最后把处理后的路径和原有的查询字符串、origin组合起来,就得到了最终的URL:

const newFullUrl = currentUrl.origin + updatedPath + currentUrl.search;
// 如果你要跳转的话,直接赋值给location.href
window.location.href = newFullUrl;

测试各种场景

这套代码能完美覆盖你提到的所有情况:

  • 原URL:/gender/category/brand/ → 处理后:/gender/category/brand/sale
  • 原URL:/gender/category/brand/?collection=short&colour=red → 处理后:/gender/category/brand/sale?collection=short&colour=red
  • 原URL:/gender/category/brand(无结尾斜杠)→ 处理后:/gender/category/brand/sale
  • 原URL:/?foo=bar → 处理后:/sale?foo=bar

为什么推荐用URL API而不是手动字符串拆分?因为它能处理所有复杂的URL场景,比如带端口的http://localhost:3000/path/、带多个查询参数的情况,完全不用自己考虑各种边界条件,省心又可靠。

内容的提问来源于stack exchange,提问作者Chobbit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:35:31