Check if String contains only Spaces in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

Check if String contains only Spaces #

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0. If the string has a length of 0 after calling the trim method, then the string contains only spaces.

index.js
function onlySpaces(str) { return str.trim().length === 0; } console.log(onlySpaces(' ')); // ๐Ÿ‘‰๏ธ true console.log(onlySpaces(' 123 ')); // ๐Ÿ‘‰๏ธ false console.log(onlySpaces('hello ')); // ๐Ÿ‘‰๏ธ false console.log(onlySpaces('')); // ๐Ÿ‘‰๏ธ true

The String.trim method removes the whitespace from both ends of a string.

We check if the result of calling the method on the string returns a string of length 0. If it does, then:

  • we have a string that contains only spaces
  • we have an empty string
The trim method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

An alternative, but also very common approach is to use a regular expression.

Check if String contains only with Regular Expression #

To check if a string contains only spaces, use the test() method with the following regular expression /^\s*$/. The test method will return true if the string contains only spaces and false otherwise.

index.js
function onlySpaces(str) { return /^\s*$/.test(str); } console.log(onlySpaces(' ')); // ๐Ÿ‘‰๏ธ true console.log(onlySpaces(' test ')); // ๐Ÿ‘‰๏ธ false console.log(onlySpaces('hello ')); // ๐Ÿ‘‰๏ธ false console.log(onlySpaces('')); // ๐Ÿ‘‰๏ธ true

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

The method returns true if the regular expression is matched in the string and false otherwise.

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

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

The \s character matches a single space, tab or newline.

The asterisk * character matches the preceding item (space) 0 or more times.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

Personally, I'm not a big fan of using regular expressions when it can be avoided. I'd recommend you use the trim method approach, as it's easier to read and more beginner friendly.

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