We can check if a string contains uppercase characters in JavaScript by checking each letter to see if that letter is uppercase in a loop. We will make use of the toUpperCase() and charAt() methods. Here is our function that will check if there are any uppercase letters in a string.
function checkUppercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toUpperCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
Notice we use a regular expression above to make sure the character is a letter.
Here is our function with a simple example:
function checkUppercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toUpperCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
console.log(checkUppercase("all letters here are lowercase"));
console.log(checkUppercase("We Have some uppercase Letters in this One."));
#Output:
false
true
When processing strings in a program, it can be useful to know if we have uppercase or lowercase characters. Using JavaScript, we can easily check if a string contains uppercase letter(s) with the help of the JavaScript toUpperCase() method.
To check if a string contains uppercase, we just need to loop over all letters in the string until we find a letter that is equal to that letter after applying the toUpperCase() method and make sure that character is a letter.
Below is our JavaScript function again which will check if a string contains an uppercase letter.
function checkUppercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toUpperCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
How to Check if a String Contains Lowercase letters in JavaScript
We can also check if a string contains lowercase characters in JavaScript very easily.
To check if a string contains lowercase letters in JavaScript, we can adjust our function that we defined above to use the JavaScript toLowerCase() method, instead of the toUpperCase() method.
Below is a JavaScript function that will check if a string contains a lowercase letter.
function checkLowercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toLowerCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
function checkLowercase(str){
for (var i=0; i<str.length; i++){
if (str.charAt(i) == str.charAt(i).toLowerCase() && str.charAt(i).match(/[a-z]/i)){
return true;
}
}
return false;
};
console.log(checkLowercase("ALL THE LETTERS ARE UPPERCASE"));
console.log(checkLowercase("We Have some uppercase Letters in this One."));
#Output:
false
true
Hopefully this article has been useful for you to learn how to check if a string contains uppercase letters JavaScript.