Borislav Hadzhiev
Thu Oct 21 2021·1 min read
Photo by Pawel Szvmanski
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.
\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