Check if String contains Whitespace in JavaScript


Borislav Hadzhiev

Last updated: Jul 27, 2022


Photo from Unsplash

Check if String contains Whitespace #

Use the test() method to check if a string contains whitespace, e.g. /\s/.test(str). The test method will return true if the string contains at least one whitespace character and false otherwise.

function containsWhitespace(str) { return /\s/.test(str); } console.log(containsWhitespace(' ')); // 👉️ true console.log(containsWhitespace('hello world')); // 👉️ true console.log(containsWhitespace('')); // 👉️ false console.log(containsWhitespace('test')); // 👉️ false

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

The test 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 \s character is used to match spaces, tabs and newlines.

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

Our regular expression checks for all types of whitespace characters, including tabs \t and newlines \n.

function containsWhitespace(str) { return /\s/.test(str); } console.log(containsWhitespace('hello\tworld')); // 👉️ true console.log(containsWhitespace('hello\nworld')); // 👉️ true

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.