Check if letter in String is Uppercase or Lowercase in JS

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Caleb George

Check if letter in String is Uppercase or Lowercase #

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.

index.js
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.

index.js
const char = 'B'; console.log(char.toUpperCase()); // ๐Ÿ‘‰๏ธ 'B' console.log(char === char.toUpperCase()); // ๐Ÿ‘‰๏ธ true

Otherwise, the letter is lowercase.

index.js
const char = 'b'; console.log(char.toUpperCase()); // ๐Ÿ‘‰๏ธ 'B' console.log(char === char.toUpperCase()); // ๐Ÿ‘‰๏ธ false
However, this approach wouldn't work with digits or punctuation, because they can't be uppercase or lowercase.
index.js
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.

index.js
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:

  1. Check if the letter's uppercase variant is equal to the letter
  2. Check if the letter is not equal to it's lowercase variant

Both conditions have to be met for us to conclude it is an uppercase letter.

We basically check if the letter has uppercase and lowercase variants at all, because digits and punctuation characters do not.
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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee