Check if String contains only Letters and Spaces in JS


Borislav Hadzhiev

Wed Oct 20 20212 min read


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.

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:

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 #

Use the search field on my Home Page to filter through my more than 1,000 articles.