原文: 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:
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;
}
Comments
So what do you think? Did I miss something? Is any part unclear? Leave your comments below.
comments powered by Disqus