Check if letter in String is Uppercase or Lowercase in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 called 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 issue, 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'); }

There are 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.