RegExp 可以与 match
方法一起用于输入字符串。
为了确保在 case
子句中有匹配项,我们将测试原始的 str
值(提供给 switch
语句)与成功 match
的 input
属性相匹配。
input
是正则表达式的静态属性,它包含原始输入字符串。
当 match
失败时,它返回 null
。为了避免异常错误,在访问 input
属性之前,我们使用可选链操作符(或传统 ES 中的逻辑 ||
条件运算符)。
const str = 'XYZ test';
switch (str) {
case str.match(/^xyz/)?.input:
console.log("Matched a string that starts with 'xyz'");
break;
case str.match(/test/)?.input:
console.log("Matched the 'test' substring");
break;
default:
console.log("Didn't match");
break;
}
另一种方法是使用
String()
构造函数将结果数组转换为字符串。该数组必须只有一个元素(没有捕获组),并且必须用量词(
.*
)捕获整个字符串。如果失败,
null
对象将变成一个
'null'
字符串。这可能看起来不太方便。
const str = 'XYZ test';
switch (str.toLowerCase()) {
case String(str.match(/^xyz.*/i)):
console.log("Matched a string without case sensitivity");
break;
case String(str.match(/.*tes.*/)):
console.log("Matched a string using a substring 'tes'");
break;
}
无论如何,更优雅的解决方案是使用
test
方法而不是
match
,即
/^find-this-in/.test(str)
与
switch (true)
一起使用,它只返回一个布尔值,并且更容易进行大小写不敏感的匹配。
const str = 'haystack';
switch (true) {
case /^hay.*/i.test(str):
console.log("Matched a string that starts with 'hay'");
break;
}
然而,在这种情况下,使用 if
、else
和 else if
语句也很容易理解。