如何在 Javascript 中将 reg exp 包含到 switch case 字符串中

How to include a reg exp into a switch case string in Javascript

我想使用 switch case 和正则表达式来压缩不同的 url。

这是我创建的代码,但它似乎没有有效地工作:

url = window.location.pathname;
switch(url){
    case /\/(en|fr|de|es)\/page1\/: myvar="page1"; break;
    case /\/(en|fr|de|es)\/page2\/: myvar="page2"; break;
    ...
}

谢谢

A case 会将提供的表达式计算为布尔值,并在必要时采取该操作。我能看到使用 switch case 执行此操作的唯一真实方法是:

let url = window.location.pathname;

switch (true) {
  case /^mytest$/.test(url):
    ...
    break;
}

话虽如此,我真的完全不建议这样做。

我不完全确定你需要从原始字符串中得到什么,但看起来剥离语言环境段并将剩下的作为页面会更容易?