文章

Switch Case statement for Regex matching in JavaScript

Switch Case statement for Regex matching in JavaScript.

原文: https://stackoverflow.com/questions/47281147/switch-case-statement-for-regex-matching-in-javascript

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}
本文由作者按照 CC BY 4.0 进行授权