Switch Case statement for Regex matching in JavaScript

Viewed 7825

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?

2 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;
}

You can use "not null":

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