Check if a String is all Uppercase in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 22 20212 min read

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 #

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