Kodeclik Blog


How to check if a letter is uppercase in Javascript

Given a string how can we check if a letter in the string is uppercase? To understand how to do this, we will write a Javascript program and embed it inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“How to check if a letter is uppercase in Javascript”) and a body with an empty script tag. Any HTML markup goes inside the body tags and any Javascript code goes inside the script tags.

Checking if a letter is uppercase

Let us write a simple program to inspect the first character of a string and determine if it is uppercase. To this end, we use the toUpperCase() method to convert the letter, and, if the letter stays the same it implies that it was uppercase in the first place.
The output of this program is:
Recall the difference between Javascript’s == and ===. The former does type casting before checking for equality whereas the latter is a strict check for equality without any conversion of typesLet us try updating the above code to inspect the second character:
The output is:
So far so good. Let us write a program to inspect every character in the string:
Here we use a for loop to iterate over all characters in the string. The output is:
Most of the output above looks good save for these two lines:
Note that the test fails for non-alphabetical characters such as the space in the string. Similarly if you had digits or other punctuation characters, the test would fail. To account for situations like this, let us first check if the character is even a letter (which means that it should pass the toUpperCase method test and fail a toLowerCase method test, or vice versa). The below code accomplishes what we want:
The output is:
As you can see the two space characters are now correctly determined to be “something else” while the other characters are correctly classified as either uppercase or lowercase.
If you liked this blogpost and analyzing strings, checkout our blogpost on four different methods to reverse a string in Javascript.
Interested in learning more Javascript? Learn how to loop through two Javascript arrays in coordination and how to make a Javascript function return multiple values!
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2023. All rights reserved.