During the for loop iteration i does not get incremented if a non-alphabetical character is detected in the if statement.
The nonnumeric function returns true if the character is non-alphabetical else it returns false. When I tested the code inside the for loop I had the console print out the value of i. Whenever the code reached a non-alphabetical character i would not get incremented and thus would create an infinite for loop.
function isUpper(str){
for(i = 0; i < str.length; i++){
if(str.charAt(i) == str.charAt(i).toUpperCase()){
if(!nonnumeric(str.charAt(i))){
return true;
};
};
};
return false;
};
I expect it to return true if there is an uppercase character inside the string. If there is not an uppercase character in the string I expect it to return false.
If you are checking to see if an entire string is uppercase, you can do something much easier.
function isUpper(str) {
return /^[A-Z\s\W]+$/.test(str);
}
console.log(isUpper('ALL UPPER CASE'));
console.log(isUpper('ALL UPPER CASE! WITH ~@# STUFF'));
console.log(isUpper('THIS hAS ONE LOWER CASE CHARACTER'));
console.log(isUpper('THIS HAS 1 NUMBER'));
The regex checks if the entire string from start (^
) to end ($
) matches the characters enclosed in the []
, which is a range of from capital A through capital Z (A-Z
, the special "space" character \s
, and other non-word characters \W
, matching one or more times. You could fine-tune this to make sure that it matches at least one capital letter, followed optionally by spaces, commas, exclamation points, etc. It all depends on your use cases and what the expected input vs. output would be
Hadn't read the last sentence under the code. If all you want is to check for an uppercase character somewhere in the string, you could simply have
function isUpper(str) {
return /[A-Z]/.test(str)
}
console.log(isUpper('ALL UPPER CASE'));
console.log(isUpper('ALL UPPER CASE! WITH ~@# STUFF'));
console.log(isUpper('THIS hAS ONE LOWER CASE CHARACTER'));
console.log(isUpper('THIS HAS 1 NUMBER'));
console.log(isUpper('this has no uppercase characters at all'));