Check if String contains only Letters in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if String contains only Letters #

Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/.test(str). The test method will return true if the string contains only letters and false otherwise.

index.js
function onlyLetters(str) { return /^[a-zA-Z]+$/.test(str); } console.log(onlyLetters('hello')); // 👉️ true console.log(onlyLetters('hello123')); // 👉️ false console.log(onlyLetters('one,two')); // 👉️ false
If you also need to match spaces, dots, commas, etc, scroll down to the next code snippet.

We used the RegExp.test method to check if a string contains only letters.

The only parameter the method takes is a string against which the regular expression is matched.

The test method returns true if the string is matched in the regex and false otherwise.

The forward slashes / / mark the beginning and end of the regular expression.

The caret ^ matches the beginning of the input and the dollar sign $ matches the end of the input.

The part between the square brackets [] is called a character class and matches a range of lowercase a-z and uppercase A-Z letters.

The plus + matches the preceding item (the letter ranges) 1 or more times.

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

If you also need to match dots, commas or spaces, etc, add the character you need to match between the square brackets [].

index.js
function onlyLettersSpacesDots(str) { return /^[a-zA-Z\s.,]+$/.test(str); } console.log(onlyLettersSpacesDots('hello world')); // 👉️ true console.log(onlyLettersSpacesDots('hello.world')); // 👉️ true console.log(onlyLettersSpacesDots('hello,world')); // 👉️ true console.log(onlyLettersSpacesDots('hello123')); // 👉️ false

In this example we match letters, whitespace characters (\s), dots and commas.

The \s special character matches spaces, tabs and new lines.

You can update the characters between the square brackets according to your use case.

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.