Check if String contains only Letters and Spaces in JS

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Anonymous

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 / / denote the start and end of the regular expression.

The caret ^ symbol matches the beginning of the input and the $ character - the end of the input.

The part between the square brackets [] is called a character class and we use it to match all uppercase and lowercase letters and spaces.

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

And 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, it has served me well over the years.

In summary our 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 #

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