Check if String contains any Letter in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Check if String contains any Letter #

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.

index.js
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:

  • all lowercase letters a-z
  • all uppercase letters 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.

index.js
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.

This achieves the same result and it's a matter of personal preference which solution you find more readable and intuitive.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee