考虑以下代码
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)
最佳答案
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);