Skip to content Skip to sidebar Skip to footer

Switch Case Statement For Regex Matching In 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(samples

Solution 1:

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

Solution 2:

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

Try to add break;

Post a Comment for "Switch Case Statement For Regex Matching In Javascript"