首页 > 解决方案 > 带有 include() 的 url 检查器

问题描述

我正在尝试用 js 制作一个 url 检查器,这是我遇到问题的代码部分:

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

我正在使用的网址是{example.com}/account/profiles/mylist,当我测试/mylist时,它一直向我显示“查看帐户...”我可以更改什么以使/account不干扰/mylist

标签: javascripttypescriptpathinclude

解决方案


这里的问题是它同时{example.com}/account/profiles/mylist包含字符串和. 因此,当您遇到第一个案例时,就会进行匹配,然后您就退出了开关。"/account""/mylist"break

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.includes("/account"):
    console.log("Viewing account...");
    break;
  case pathname.includes("/mylist"):
    console.log("Viewing list...");
    break;
}

如果您知道/mylist在层次结构中总是会更深,在下面/account,您可以切换案例的顺序:

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.includes("/mylist"):
    console.log("Viewing list...");
    break;
  case pathname.includes("/account"):
    console.log("Viewing account...");
    break;
}

否则,您可能需要更细微的逻辑方法,并且您可能希望避免使用switch支持if/else语句的语句,因为 a 有一些特殊性switch(特别是,一旦满足单个案例,所有其他案例块将被解释为匹配直到你break)。

编辑:

或者,另一种选择是利用endsWith

let pathname = '/account/profiles/mylist';
switch (true) {
  case pathname.endsWith("/account"):
    console.log("Viewing account...");
    break;
  case pathname.endsWith("/mylist"):
    console.log("Viewing list...");
    break;
}

全面披露- 当我输入此编辑时,esqew 发布了相同的解决方案


推荐阅读