简体   繁体   English

JS:switch case 中的正则表达式

[英]JS : Regular expression in switch case

I try to test a specific string with a switch case and I find this code :我尝试用 switch case 测试一个特定的字符串,我发现这个代码:

let prop = "date myData";
switch (true) {
          case /str/.test(prop) :
            console.log("tata");
            break;

          case /date/.test(prop):
            console.log("toto");
            break;

          case /enum/.test(prop) :
            console.log("titi");
            break
          default :
            console.log("Nada");
            break;
}

It works but it don't resolve my problem.它有效,但不能解决我的问题。 I want to get specifically the string "date" for example.例如,我想特别获取字符串“日期”。 With nothing before and nothing after.之前一无所有,之后一无所有。

I this example, I want my console to display "Nada".在这个例子中,我希望我的控制台显示“Nada”。

I don't know how to do that with this code.我不知道如何用这段代码做到这一点。 A solution ?一个办法 ? :) :)

You need either start and end signs in the regular expression您需要正则表达式中的开始和结束符号

/^date$/

or a simple test with a string and equality或带有字符串和相等性的简单测试

prop === 'date'

or或者

switch (prop) {
    case 'date':
        console.log('date');
        break;
}

For what you have there a switch is not your first choice - also you are just comparing strings for equality - so an easier way would be the following对于你有的东西, switch 不是你的第一选择 - 你也只是比较字符串的相等性 - 所以更简单的方法是以下

 let prop = "date myData"; let strings = {str: "tata", date: "toto", enum:"titi"} let res = strings[prop] || "Nada"; console.log(res);

To test for equality to multiple strings, either stack case statements like this:要测试多个字符串是否相等,可以像这样堆栈 case 语句:

switch (true) {
  case prop === "date":
  case prop === "param2":
    // Do something
    break;
}

Or test for inclusion in a static array:或者测试是否包含在静态数组中:

switch (true) {
  case ["date", "param2"].includes(prop):
    // Do something
    break;
}

Although switching on true is probably not the most efficient way to do this.尽管打开true可能不是最有效的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM