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

使用JS的includes()开发URL检测工具时路径匹配干扰问题如何解决

问题原因

switch (true) 会按照case的书写顺序依次校验条件是否成立,只要命中第一个为真的条件就会执行对应分支的逻辑,不会再校验后续case。你的测试路径/account/profiles/mylist同时包含/account和/mylist两个字符串,且/account的判断逻辑写在更靠前的位置,所以永远会优先命中/account分支。

解决方法

方法1:调整case优先级顺序

把匹配范围更小、更具体的规则放到更靠前的位置,优先校验/mylist的条件即可:

switch (true) {
    case document.location.pathname.includes("/mylist"):
      presenceData.details = "Viewing list..."
    break
    case document.location.pathname.includes("/account"):
      presenceData.details = "Viewing account..."
    break
}

方法2:增加匹配规则的精准度

如果不想依赖case的书写顺序,可以给路径匹配增加限定条件,避免模糊匹配互相干扰,比如可以限定/account仅匹配路径前缀,且路径中不包含/mylist:

switch (true) {
    case document.location.pathname.includes("/mylist"):
      presenceData.details = "Viewing list..."
    break
    case document.location.pathname.startsWith("/account") && !document.location.pathname.includes("/mylist"):
      presenceData.details = "Viewing account..."
    break
}

如果后续路径规则更复杂,也可以考虑把路径按/分割成数组后按位置匹配,或者改用if-else分支编写逻辑,可读性会更高。

内容的提问来源于stack exchange,提问作者anão

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:15:07