Reputation: 3399
Consider the following Code
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);
Essentially I need to recognize separately if a lower case and UPPER case character exists. Notice each sample string will trigger either the UPPER or lower case condition, but both should trigger both.
The complexity count for both examples should be 3. What am I doing wrong with my regex?
(no jQuery please)
Upvotes: 1
Views: 44
Reputation: 40
So a easy way to achieve what you want is this but I didnt use search
function hasLowerCase(str) {
if(str.toUpperCase() != str) {
return true;
}
return false;
}
Upvotes: 0
Reputation: 929
You should use test instead. Your question looked like you wanted to combine the upper and lower test. I did this in the below.
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);
Upvotes: 2
Reputation: 92461
string.search()
returns the first index of the found item, which in the case of you Upper Case search is 0, which evaluates to false.
Try using regex.test()
instead:
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);
Upvotes: 4