Categories
JavaScript Answers

How to Check if a String Contains Characters and a Whitespace and Not Just a Whitespace?

Spread the love

Sometimes, we want to check if a string has characters and whitespace and not just whitespace.

In this article, we’ll look at how to check if a string has characters and whitespace and not just whitespace.

Check if a String has Non-whitespace Characters

We can use the S pattern to check if a string has any non-whitespace characters.

For instance, we can write:

const myString = 'abc '

if (/S/.test(myString)) {
  //...
}

to check if myString has any non-whitespace characters with the regex test method.

It should return true since it has non-whitespace characters.

Use the String.prototype.trim Method

Another way to check if a string has non-whitespace characters is to use the JavaScript string’s trim method.

For instance, we can write:

const myString = 'abc '

if (!myString.trim()) {
  //...
}

If myString returns an empty string after calling trim on it, then it only has whitespaces.

Therefore, we can check if trim returns a falsy value to do the whitespace-only check since empty string is a falsy value.

Check if a String has Only Whitespace Characters

We can also check if a string only has whitespace characters.

To do this, we write:

const myString = 'abc '

if (/^s+$/.test(myString)) {
  //...
}

We call test with /^s+$/ to check if myString only has whitespace characters.

The ^ indicates the start of the string and $ indicates the end of the string.

s+ is the pattern for one or more whitespace characters.

So the regex checks if the whole string consists of whitespaces.

Conclusion

We can use various regex patterns or the trim method to check if a string has all whitespace or not.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *