在switch语句中使用正则

方法1

1
2
3
4
5
6
7
8
9
var str = "abcxyz";
switch(true) {
case /xyz/.test(str) :
console.log("1");
break;
default:
console.log("0");
break;
}

方法2

1
2
3
4
5
6
7
8
9
var str = "abcxyz";
switch(str) {
case (str.match(/xyz/) || {}).input :
console.log("1");
break;
default:
console.log("0");
break;
}

方法3

1
2
3
4
5
6
7
8
9
var str = "abcxyz";
switch(str) {
case (/xyz/.test(str) ? str : NaN) : //输入值为NaN时不命中
console.log("1");
break;
default:
console.log("0");
break;
}

switch-statement-for-string-matching-in-javascript - Stack Overflow