How to detect string which contains only spaces?

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0, then you can be sure the original only contained whitespace. Try this:

var str = "    ";
if (!str.replace(/\s/g, '').length) {
  console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Edit: After looking at this a few years later I noticed this could be simplified further. Since the result of trim will either be truthy or falsy you can also do the following:

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

Solution 4 - Javascript

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

String#trim() removes the whitespace at the start and end of the string. If the string contained only whitespace, it would be empty after trimming, and the empty string is falsey in JavaScript.

If the string might be null or undefined, we need to first check if the string itself is falsey before trimming.

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
}

Solution 5 - Javascript

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"

Solution 6 - Javascript

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");
}

Solution 7 - Javascript

If we want to check if string contains only white spaces, then this might be helpful.

const str = '   ';
console.log(/\s/.test(str));

This will log true.

Solution 8 - Javascript

This works in Dart not Javascript. However, when I searched up how to do this with Dart this question came up, so I figured others may need the Dart answer.

String foo = '        ';
if (foo.replaceAll(' ', '').length == 0) {
print('ALL WHITE SPACE');
}
else {
print('NOT ALL WHITE SPACE');
}

To further clarify, the String ' d ' will print 'NOT ALL WHITE SPACE' and the String ' ' will print 'ALL WHITE SPACE'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucaView Question on Stackoverflow
Solution 1 - JavascriptRory McCrossanView Answer on Stackoverflow
Solution 2 - JavascriptpmrotuleView Answer on Stackoverflow
Solution 3 - Javascriptbobbyg603View Answer on Stackoverflow
Solution 4 - JavascriptUnmitigatedView Answer on Stackoverflow
Solution 5 - JavascriptShehzadView Answer on Stackoverflow
Solution 6 - Javascriptuser3024615View Answer on Stackoverflow
Solution 7 - Javascriptsabir hassanView Answer on Stackoverflow
Solution 8 - JavascriptMatthew TrentView Answer on Stackoverflow