9

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?

3
  • 1
    I think you skipped break.
    – kyun
    Nov 14, 2017 at 8:43
  • Every case that comes after the one that was matched will be executed, unless the browser reads the break keyword.
    – barbarossa
    Nov 14, 2017 at 8:49
  • i added the break keyword but it still doesnt work
    – J.Doe
    Nov 14, 2017 at 8:49

2 Answers 2

21

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

2
  • this works but i read somewhere that this isnt a very clean method of doing a switch case statement, is this true?
    – J.Doe
    Nov 14, 2017 at 8:51
  • it's a clean pattern beside that it works as intended. Nov 14, 2017 at 8:53
0

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");
}
1
  • I tried it in Typescript and got the error Type 'boolean' is not comparable to type 'string'.ts(2678) May 22 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.