Check if String contains any Letters in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if String contains any Letters #

To check if a string contains any letters, 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 containsAnyLetters(str) { return /[a-zA-Z]/.test(str); } console.log(containsAnyLetters('abc123')); // 👉️ true console.log(containsAnyLetters('ABC')); // 👉️ true console.log(containsAnyLetters('123')); // 👉️ false console.log(containsAnyLetters(' ')); // 👉️ false if (containsAnyLetters('hello')) { // 👇️ this runs 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 beginning 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.

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 containsAnyLetters(str) { // 👇️ using the `i` flag return /[a-z]/i.test(str); } console.log(containsAnyLetters('A1')); // 👉️ true console.log(containsAnyLetters('! !')); // 👉️ true if (containsAnyLetters('abc123')) { // 👇️ this runs console.log('✅ string contains a letter'); } else { console.log('⛔️ string does NOT contain a letter'); }

Instead of using the range of uppercase letters A-Z, we used the i flag for case-insensitive search.

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

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.