Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Morgan Sessions
To check if a string contains any letter, use the test()
method with the
following regular expression /[a-zA-Z]/
. The test
method will return true
if the string contains at least one letter and false
otherwise.
function containsAnyLetter(str) { return /[a-zA-Z]/.test(str); } console.log(containsAnyLetter('abc123')); // 👉️ true console.log(containsAnyLetter('ABC')); // 👉️ true console.log(containsAnyLetter('123')); // 👉️ false console.log(containsAnyLetter(' ')); // 👉️ false if (containsAnyLetter('hello')) { console.log('✅ string contains a letter'); } else { console.log('⛔️ string does NOT contain a letter'); }
We used the RegExp.test method to check if a string contains at least 1 letter.
The test
method returns true
if the regular expression is matched in the
string and false
otherwise.
The forward slashes / /
mark the start and end of the regular expression.
The square brackets []
are called a character class. In the character class we
match 2 ranges:
a-z
A-Z
If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.
Instead of using 2 ranges for lowercase and uppercase letters, we can also
perform a case insensitive match, by using the i
flag.
function containsAnyLetter(str) { // 👇️ using the `i` flag return /[a-z]/i.test(str); } console.log(containsAnyLetter('A1')); // 👉️ true console.log(containsAnyLetter('! !')); // 👉️ true if (containsAnyLetter('abc123')) { console.log('✅ string contains a letter'); } else { console.log('⛔️ string does NOT contain a letter'); }
In this regular expression, we use the i
flag for case insensitive search,
instead of using the range of uppercase letters A-Z
.