How to check if character is a letter in Javascript?
Solution 1:
I don't believe there is a built-in function for that. But it's easy enough to write with a regex
function isLetter(str) {
return str.length === 1 && str.match(/[a-z]/i);
}
Solution 2:
With respect to those special characters not being taken into account by simpler checks such as /[a-zA-Z]/.test(c)
, it can be beneficial to leverage ECMAScript case transformation (toUpperCase
). It will take into account non-ASCII Unicode character classes of some foreign alphabets.
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
NOTE: this solution will work only for most Latin, Greek, Armenian and Cyrillic scripts. It will NOT work for Chinese, Japanese, Arabic, Hebrew and most other scripts.