November 4, 2023
JavaScript does not have a built-in isUpperCase
function, but checking whether a string is uppercase is a common task during string manipulation. In this guide we’ll explain how to determine if a character or a string is in uppercase using JS.
Understanding character codes
Each character in a string has an associated Unicode value which can be used to determine its case. For standard English letters, uppercase characters have code points from 65 ('A') to 90 ('Z').
const charCode = 'A'.charCodeAt(0); console.log(charCode); // 65
Using a regular expression
A regular expression can check if a string consists solely of uppercase characters:
const isUpperCase = (str) => /^[A-Z]+$/.test(str); console.log(isUpperCase("HELLO")); // true console.log(isUpperCase("Hello")); // false
Checking individual characters
If you want to check individual characters instead of the whole string:
const isCharUpperCase = (char) => char === char.toUpperCase(); console.log(isCharUpperCase("H")); // true console.log(isCharUpperCase("h")); // false
Iterating over strings
To determine if every character in a string is uppercase, iterate over them:
const isFullyUpperCase = (str) => { for (let i = 0; i < str.length; i++) { if (str[i] !== str[i].toUpperCase()) { return false; } } return true; };
Handling non-English characters
Be cautious with non-English characters. toUpperCase
might not behave as expected with characters that don't have a distinct uppercase form.
console.log(isCharUpperCase("ß")); // false, even though "ß".toUpperCase() is "SS"
Using locale-specific methods
For locale-aware case conversions, use toLocaleUpperCase
:
const isCharUpperCaseLocale = (char, locale) => char === char.toLocaleUpperCase(locale); console.log(isCharUpperCaseLocale("i", "tr-TR")); // true for Turkish locale
Edge cases to consider
- Non-alphabetic characters: Decide if you need to treat them as uppercase, lowercase, or neither.
- Empty strings: Define what the return value should be for an empty string input.
- Case conversion exceptions: Some characters don't convert neatly between cases, such as the German "ß".
Performance considerations
Regular expressions are convenient but might not be as fast as a loop-based approach for long strings. Always consider the context and the size of the data when choosing your method.
Ship faster, worry less with Basedash
How to Sort Object Array by Boolean Property in JavaScript
Max Musing
How to Truncate Date in MySQL
Max Musing
What is evented I/O for V8 JavaScript?
Max Musing
Replace + with Space in JavaScript
Max Musing
How to Sort JavaScript Objects by Key
Max Musing
How to Scroll Automatically to the Bottom of a Page in JavaScript
Max Musing