How to Check Case of Letter in JavaScript ?
Last Updated :
23 Jan, 2024
There are different ways to check the case of the letters in JavaScript which are explained below comprehensively, one can choose the method that best suits their specific use case and requirement.
Using the function “toUpperCase()” or “toLowerCase”
Javascript has toUpperCase() and toLowerCase() methods by using these methods one can convert the string to an upper case or lower case letter and then use it to compare it with the original letter to determine the case of the letter.
Syntax:
character.toUpperCase();
Example: Demonstrating the use of the “toUpperCase()” and “toLowerCase()” methods to determine the case of the letters in JavaScript.
Javascript
function checkCase(character) {
if (character ===
character.toUpperCase()) {
return 'Uppercase' ;
} else if (character ===
character.toLowerCase()) {
return 'Lowercase' ;
} else {
return 'Mixed case' ;
}
}
console.log(checkCase( "G" ));
console.log(checkCase( "g" ));
console.log(checkCase( "GeeksforGeeks" ));
|
Output
Uppercase
Lowercase
Mixed case
Using regular expression
One can use regular expressions to check whether the letters are in upper case or lower case.
Syntax:
/[A-Z]/ // Regex for only uppercase letters
Example: Demonstrating the use of the regular expression to check the case of the letter.
Javascript
function checkCase(character) {
return (/[A-Z]/.test(character)) ? 'Uppercase' : 'Lowercase' ;
}
console.log(checkCase( "G" ))
console.log(checkCase( "g" ))
|
Output
Uppercase
Lowercase
Using ASCII value
ASCII values can also be used to check the case of the letter as the ASCII values between 65 and 90 are in upper case while the ASCII values from 97 to 122 are in lower case.
Example: Demonstrating the use of ASCII to determine the case of the letter.
Javascript
function checkCase(str) {
if (str.charCodeAt(0) >= 65 &&
str.charCodeAt(0) <= 90) {
console.log( "Letter is UppperCase" )
}
else if (str.charCodeAt(0) >= 97 &&
str.charCodeAt(0) <= 122) {
console.log( "Letter is in lowerCase" )
}
}
checkCase( "G" )
checkCase( "g" )
|
Output
Letter is UppperCase
Letter is in lowerCase
Share your thoughts in the comments
Please Login to comment...