Borislav Hadzhiev
Wed Oct 20 2021·2 min read
Photo by Caleb George
To check if a letter in a string is uppercase or lowercase use the
toUpperCase()
method to convert the letter to uppercase and compare it to
itself. If the comparison returns true
, then the letter is uppercase,
otherwise it's lowercase.
const letter = 'A'; if (letter.toUpperCase() === letter) { console.log('✅ letter is uppercase'); } else { console.log('⛔️ letter is lowercase'); }
We call the String.toUpperCase method to convert the character to uppercase so we can compare it.
If comparing the uppercase variant of the letter to the letter itself returns
true
, then the letter was uppercase to begin with.
const char = 'B'; console.log(char.toUpperCase()); // 👉️ 'B' console.log(char === char.toUpperCase()); // 👉️ true
Otherwise, the letter is lowercase.
const char = 'b'; console.log(char.toUpperCase()); // 👉️ 'B' console.log(char === char.toUpperCase()); // 👉️ false
const letter = '?'; if (letter.toUpperCase() === letter) { // 👉️ this runs... console.log('✅ letter is uppercase'); } else { console.log('⛔️ letter is lowercase'); }
To solve this problem, we have to check if the letter has uppercase and lowercase variants.
const letter = '?'; if (letter.toUpperCase() === letter && letter !== letter.toLowerCase()) { console.log('✅ letter is uppercase'); } else { // 👉️ this runs console.log('⛔️ letter is lowercase'); }
We have 2 conditions in our if
statement:
Both conditions have to be met for us to conclude it is an uppercase letter.
const str = '4'; // 👇️️ true console.log(str.toLowerCase() === str.toUpperCase());
If we know that the letter is uppercase and it's not equal to it's lowercase variant, then we have an uppercase letter.
Otherwise, we have a lowercase letter, a digit or punctuation.