Check if String contains only Letters and Spaces in JS

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Check if String contains only Letters and Spaces #

To check if a string contains only letters and spaces, call the test() method on a regular expression that matches only letters and spaces. The test method will return true if the regular expression is matched in the string and false otherwise.

index.js
const str1 = 'only letters and spaces'; const str2 = 'one-two-three'; function onlyLettersAndSpaces(str) { return /^[A-Za-z\s]*$/.test(str); } console.log(onlyLettersAndSpaces(str1)); // 👉️ true console.log(onlyLettersAndSpaces(str2)); // 👉️ false

We called the RegExp.test method to check if the string contains only letters and spaces.

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

The caret ^ symbol 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 all uppercase and lowercase letters and spaces.

The A-Z and a-z characters match a range of uppercase and lowercase letters.

The \s character matches a single whitespace character.

The asterisk * matches the preceding item (our character class) zero or more times.

If you need help reading a regular expression, check out this regex cheatsheet by the MDN docs.

In its entirety, the regular expression checks if the string contains only uppercase and lowercase letters or spaces from start to finish.

If the condition is met, the test method returns true, otherwise it returns false.

Here are some more examples:

index.js
const str1 = 'hello 42'; const str2 = 'one more time'; const str3 = 'Try this.'; function onlyLettersAndSpaces(str) { return /^[A-Za-z\s]*$/.test(str); } console.log(onlyLettersAndSpaces(str1)); // 👉️ false console.log(onlyLettersAndSpaces(str2)); // 👉️ true console.log(onlyLettersAndSpaces(str3)); // 👉️ false

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.