假设 cad 是foo:
// will return false
if (cad.match(new RegExp("[A-Z]"))) {
resultado="mayúsculas";
// so will go there
} else {
// will return true
if (cad.match(new RegExp("[a-z]"))) {
// so will go there
resultado="minúsculas";
} else {
if (cad.match(new RegExp("[a-zA-z]"))) {
resultado = "minúsculas y MAYUSCULAS";
}
}
}
现在,假设 cad 是FOO:
// will return true
if (cad.match(new RegExp("[A-Z]"))) {
// so will go there
resultado="mayúsculas";
} else {
if (cad.match(new RegExp("[a-z]"))) {
resultado="minúsculas";
} else {
if (cad.match(new RegExp("[a-zA-z]"))) {
resultado = "minúsculas y MAYUSCULAS";
}
}
}
最后,假设 cad 是FoO:
// will return true
if (cad.match(new RegExp("[A-Z]"))) {
// so will go there
resultado="mayúsculas";
} else {
if (cad.match(new RegExp("[a-z]"))) {
resultado="minúsculas";
} else {
if(cad.match(new RegExp("[a-zA-z]"))) {
resultado = "minúsculas y MAYUSCULAS";
}
}
}
如您所见,嵌套else从未被访问过。
你可以做的是:
if (cad.match(new RegExp("^[A-Z]+$"))) {
resultado="mayúsculas";
} else if (cad.match(new RegExp("^[a-z]+$"))) {
resultado="minúsculas";
} else {
resultado = "minúsculas y MAYUSCULAS";
}
解释:
^表示从字符串的开头,
$表示到字符串的末尾,
<anything>+至少意味着任何东西。
也就是说,
^[A-Z]+$意味着字符串应该只包含大写字符,
^[a-z]+$意味着字符串应该只包含小写字符。
因此,如果字符串不仅由大写或小写字符组成,则字符串包含它们两者。