Check if String contains Whitespace in JavaScript

avatar

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.

index.js
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.

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

Further Reading #

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