考虑以下代码
var theValue = 'Monkey123' //UPPER CASE Missed
//var theValue = 'abcABC123!' //lower case Missed
currentComplexityCount = 0;
if (theValue.search(/[a-z]/g)) {
currentComplexityCount++;
console.log('lower case hit');
}
if (theValue.search(/[A-Z]/g)) {
currentComplexityCount++;
console.log('UPPER case hit');
}
if (theValue.search(/[0-9]/g)) {
currentComplexityCount++;
console.log('Number hit');
}
console.log('Your complexity Count: ' + currentComplexityCount);
从本质上讲,如果存在小写和大写字符,则需要分别识别 。请注意,每个示例字符串都将触发大写或小写条件,但两者都应同时触发。
两个示例的复杂度计数应为3。我的正则表达式在做什么?
(请不要使用jQuery )
答案 0 :(得分:4)
string.search()
返回找到的项目的第一个索引,在您使用大写字母搜索的情况下,该索引为0,其值为false。
尝试改用regex.test()
:
var theValue = 'Monkey123' //UPPER CASE Missed
currentComplexityCount = 0;
if (/[a-z]/.test(theValue)) {
currentComplexityCount++;
console.log('lower case hit');
}
if (/[A-Z]/.test(theValue)) {
currentComplexityCount++;
console.log('UPPER case hit');
}
if (/[0-9]/.test(theValue)){
currentComplexityCount++;
console.log('Number hit');
}
console.log('Your complexity Count: ' + currentComplexityCount);
答案 1 :(得分:2)
您应该改用test。您的问题看起来像是您想要组合上限和下限测试。我在下面做了这个。
var theValue = 'Monkey123' //UPPER CASE Missed
//var theValue = 'abcABC123!' //lower case Missed
currentComplexityCount = 0;
if (/[a-z]/g.test(theValue)) {
currentComplexityCount++;
console.log('lower case hit');
}
if (/[A-Z]/g.test(theValue)) {
currentComplexityCount++;
console.log('upper case hit');
}
if (/[0-9]/g.test(theValue)) {
currentComplexityCount++;
console.log('Number hit');
}
console.log('Your complexity Count: ' + currentComplexityCount);
答案 2 :(得分:0)
一个简单的方法来实现您想要的,但是我没有使用搜索
function hasLowerCase(str) {
if(str.toUpperCase() != str) {
return true;
}
return false;
}