Check if String contains Whitespace in JavaScript


Borislav Hadzhiev

Thu Oct 21 20211 min read

Check if String contains Whitespace #

To check if a string contains whitespace, use the test() method with the following regular expression /\s/. The test method will return true if the string has at least one whitespace 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 has 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 this regex cheatsheet from MDN out.

This regular expression checks for all types of whitespace characters, e.g. 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 #

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