[javascript] How to detect string which contains only spaces?

A string length which contains one space is always equal to 1:

alert('My str length: ' + str.length);

The space is a character, so:

str = "   ";
alert('My str length:' + str.length); // My str length: 3

How can I make a distinction between an empty string and a string which contains only spaces? How can I detect a string which contain only spaces?

This question is related to javascript

The answer is


The fastest solution would be using the regex prototype function test() and looking for any character that is not a space, tab, or line break \S :

if (!/\S/.test(str)) {
  // Didn't find something other than a space which means it's empty
}

In case you have a super long string, it can make a significant difference as it will stop processing as soon as it finds a non-space character.


You can Trim your String value by creating a trim function for your Strings.

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

now it will be available for your every String and you can use it as

str.trim().length// Result will be 0

You can also use this method to remove the white spaces at the start and end of the String i.e

"  hello  ".trim(); // Result will be "hello"

if(!str.trim()){
  console.log('string is empty or only contains spaces');
}

Removing the whitespace from a string can be done using String#trim().

To check if a string is null or undefined, one can check if the string itself is falsey, in which case it is null, undefined, or an empty string. This first check is necessary, as attempting to invoke methods on null or undefined will result in an error. To check if it contains only spaces, one can check if the string is falsey after trimming, which means that it is an empty string at that point.

if(!str || !str.trim()){
   //str is null, undefined, or contains only spaces
}

This can be simplified using the optional chaining operator.

if(!str?.trim()){
   //str is null, undefined, or contains only spaces
}

If you are certain that the variable will be a string, only the second check is necessary.

if(!str.trim()){
   console.log("str is empty or contains only spaces");
}

Similar to Rory's answer, with ECMA 5 you can now just call str.trim().length instead of using a regular expression. If the resulting value is 0 you know you have a string that contains only spaces.

if (!str.trim().length) {
  console.log('str is empty!');
}

You can read more about trim here.


Trim your String value by creating a trim function

var text = "  ";
if($.trim(text.length == 0){
  console.log("Text is empty");
}
else
{
  console.log("Text is not empty");
}