简体   繁体   中英

JS : Regular expression in switch case

I try to test a specific string with a switch case and I find this code :

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".

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

 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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