Check if a String is all Uppercase in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 22, 2021

banner

Photo from Unsplash

Check if a String is contained in an Array #

To check if a string is all uppercase, use the toUppercase() method to convert the string to uppercase and compare it to itself. If the comparison returns true, then the string is all uppercase.

index.js
const str = 'HELLO WORLD'; if (str.toUpperCase() === str) { // 👇️ this runs console.log('✅ string is all uppercase'); } else { console.log('⛔️ string is NOT all uppercase'); }

We used the String.toUpperCase method to convert the string to uppercase, so we can compare it.

If comparing the uppercase variant of the string to the string itself returns true, then we have an uppercase string.

index.js
const str = 'HELLO WORLD'; console.log(str.toUpperCase()); // 👉️ HELLO WORLD console.log(str === str.toUpperCase()); // 👉️ true

Otherwise, the string contains lowercase characters.

index.js
const str = 'Hello World'; console.log(str.toUpperCase()); // 👉️ HELLO WORLD console.log(str.toUpperCase() === str); // 👉️ false
However, this approach wouldn't work with digits or punctuation because they can't be uppercase or lowercase.
index.js
const str = '!!!'; if (str.toUpperCase() === str) { // 👇️ this runs ... console.log('✅ string is all uppercase'); } else { console.log('⛔️ string is NOT all uppercase'); }

To solve this problem, we have to check if the string has uppercase and lowercase variants.

index.js
const str = '!!!'; if (str.toUpperCase() === str && str !== str.toLowerCase()) { console.log('✅ string is all uppercase'); } else { // 👉️ this runs console.log('⛔️ string is NOT all uppercase'); }

We have 2 conditions in our if statement:

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

Both conditions have to be met for us to conclude the string is all uppercase.

We basically check if the string has uppercase and lowercase variants at all, because digits and punctuation characters do not.
index.js
const str = '100'; // 👇️ true console.log(str.toUpperCase() === str.toLowerCase());

If we know that the string is uppercase and it's not equal to it's lowercase variant, then we have an all uppercase string.

Otherwise the string contains at least 1 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.