To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned.
You can use the Character. isLetter(char c) method to check if a character is a valid letter. This method will return a true value for a valid letter characters and false if the character is not a valid letter.
You can check if a JavaScript string contains a character or phrase using the includes() method, indexOf(), or a regular expression. includes() is the most common method for checking if a string contains a letter or series of letters, and was designed specifically for that purpose.
JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.
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);
}
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.
if( char.toUpperCase() != char.toLowerCase() )
Will return true only in case of letter
As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.
if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )
ES6 supports unicode-aware regular expressions.
RegExp(/^\p{L}/,'u').test(str)
This works for all alphabets.
Unfortunately, there is a bug in Firefox (will be fixed in version 78) that prevents this from being used universally. But if you can control your runtime environment and it supports it (e.g. Node.js), this is a straightforward, comprehensive solution.
Atlernatively, XRegExp provides a polyfill of modern regular expression to all browsers.
I believe this plugin has the capabilities you seek: http://xregexp.com/plugins/ (github link: https://github.com/slevithan/xregexp)
With it you can simply match all unicode letters with \p{L}
.
Read the header of this source file to see which categories it supports: http://xregexp.com/plugins/xregexp-unicode-categories.js
How about using ASCII codes?
let n = str.charCodeAt(0);
let strStartsWithALetter = (n >= 65 && n < 91) || (n >= 97 && n < 123);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With