
Check If a String Contains Only Whitespace with JavaScript

There are plenty of reasons that you might need to test a variable to see whether it contains just whitespace. Whether you're dealing with user input, or manipulating data in ways where whitespace might trip you up such as validating data before converting arrays to strings, or vice‑versa.
It's not always enough to just test string length to ensure that a string has useable characters and data. So how do we check for ‑ and remove ‑ whitespace?
The JavaScript trim() method
The JavaScript trim() method is very handy and straightforward function for dealing with unexpected whitespace at the beginning or end of a string. It will remove any whitespace from either (or both) ends, whilst preserving any whitespace in the middle:
const str = ' Lots of whitespace here! ';console.log(str.trim());//=> 'Lots of whitespace here!'As you can see, this is a great function for preserving the actual useful data whilst neatening up the string ‑ something especially helpful for dealing with user inputs. However, using trim() on a string that is only whitespace will result in a string that is 0 characters long ‑ meaning that if we pair it with the length property, we end up with a neat and lightweight way to detect strings that are only whitespace.
For example:
const whitespace_str = ' ';console.log(whitespace_str.trim().length === 0);//=> Trueconst data_str = ' Data here! ';console.log(data_str.trim().length === 0);//=> FalseSimple! You can even turn this into an extremely straightforward utility function:
const onlyWhiteSpace = (string: string): boolean => string.trim().length === 0;Because the trim() method doesn't affect the original string, we don't have to worry about calling it on our variable for this test.
Using Regex to Detect Whitespace‑Only Strings
While most people would rather use the much clearer and easier‑to‑read trim() method, you could also use regex to a similar result. It's potentially a little faster, but the main benefit of making use of regex is that it gives you much more finite control if you want to match other patterns at the same time.
To detect just white space with regex, you'll need to make use of the test() method, and match any number of space characters. The expression you'll want to use looks like this:
/^\s*$/My problem with using regex for simple tasks like this is always that they look a little ugly, and aren't necessarily easy or obvious what they do when picked up by another developer on the team. Nevertheless, it breaks down like this:
- The forward slashes
/represent the start and end of the regular expression. Everything between these will be interpreted as the pattern to match against. - The caret
^marks the start of the pattern. - The backslash
\\escapes the next character, which here is ans. Without the backslash, this pattern would be searching for a string made entirely of just the charactersan unlimited number of times, but with this backslash, regex is searching for spaces. - The asterisk
*means that the preceding pattern (in this case, just the expression for a space) can repeat any number of times. This means you can find a string that is one, two, ten, twenty, or any number of spaces in a row. - The dollar sign
$marks the end of the pattern.
To use this with the test() method, I'd recommend creating a separate utility function again to try and keep things as neat as possible. That could look like this:
const onlyWhiteSpace = (string:string): boolean => /^\\s*$/.test(string);console.log(onlyWhiteSpace(' '));//=> trueconsole.log(whitespaceOnly(' Data in here! '));//=> falseThe Wrap‑Up
It's thankfully very easy to make sure you're not dealing with an empty string. Unfortunately, not quite as easy as just checking for string length, but with the trim() method (or the Regex pattern if that's what you prefer), you can ensure that you're not being deceived by any sneaky whitespaces slipping through your validation.
Categories:
Related Articles

Higher‑Order Functions in JavaScript. 
Disabling Gatsby Telemetry. Disabling Gatsby Telemetry

Declarative vs. Imperative Programming. Declarative vs. Imperative Programming

React Fragments Explained. React Fragments Explained

Use Greater‑Than and Less‑Than Symbols in JSX. Use Greater‑Than and Less‑Than Symbols in JSX

How to Find a Programmer Job. How to Find a Programmer Job

Array.find(), Array.some(), and Array.every() in JavaScript. Array.find(),Array.some(), andArray.every()in JavaScript
The Difference Between == and === in JavaScript. The Difference Between
==and===in JavaScript
Container Queries in CSS. Container Queries in CSS
Create Arrays of Any Size with Placeholder Content in JavaScript. Create Arrays of Any Size with Placeholder Content in JavaScript

Positioning in CSS. Positioning in CSS

Solving the 'Letter Combinations of a Phone Number' Problem with TypeScript. Solving the 'Letter Combinations of a Phone Number' Problem with TypeScript