Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Case statement for Regex matching in JavaScript

Tags:

javascript

So I have a bunch of regexes and I try to see if they match with another string using this If statement:

if (samplestring.match(regex1)) {
  console.log("regex1");
} else if (samplestring.match(regex2)) {
  console.log("regex2");
} else if (samplestring.match(regex3)) {
  console.log("regex3");
}

But as soon as I need to use more regexes this gets quite ugly so I want to use a switch case statement like this:

switch(samplestring) {
  case samplestring.match(regex1): console.log("regex1");
  case samplestring.match(regex2): console.log("regex2");
  case samplestring.match(regex3): console.log("regex3");
}

The problem is it doesn't work like I did it in the example above. Any Ideas on how it could work like that?

like image 463
J.Doe Avatar asked Jan 03 '23 05:01

J.Doe


1 Answers

You need to use a different check, not with String#match, that returns an array or null which is not usable with strict comparison like in a switch statement.

You may use RegExp#test and check with true:

var regex1 = /a/,
    regex2 = /b/,
    regex3 = /c/,
    samplestring = 'b';

switch (true) {
    case regex1.test(samplestring):
        console.log("regex1");
        break;
    case regex2.test(samplestring):
        console.log("regex2");
        break;
    case regex3.test(samplestring):
        console.log("regex3");
        break;
}
like image 51
Nina Scholz Avatar answered Jan 12 '23 03:01

Nina Scholz