How to check if character is a letter in Javascript?
Serhii Shramko /
There my favorite and reliable methods to check if a character is a letter.
Using ASCII Code Values
Another common method is checking ASCII code values using charCodeAt()
:
function isLetter(char) {
const code = char.charCodeAt(0);
return (code >= 65 && code <= 90) || // uppercase letters
(code >= 97 && code <= 122); // lowercase letters
}
console.log(isLetter('A')); // true
console.log(isLetter('z')); // true
console.log(isLetter('5')); // false
Why it works ASCII
Using String Methods
A simple but less performant method uses a combination of toUpperCase()
and toLowerCase()
:
function isLetter(char) {
return char.toLowerCase() !== char.toUpperCase();
}
console.log(isLetter('A')); // true
console.log(isLetter('!')); // false
This method is the most marvelous 🦄
Letters have different uppercase and lowercase versions, while non-letters (like numbers and special characters) remain unchanged when using these case conversion methods.