Reputation: 20919
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?
Upvotes: 143
Views: 205397
Reputation: 1043
Typecasting to Number
can detect whitespace-only strings (if strings containing only zeros can be excluded):
if (+' ' === 0) console.log('is whitespace');
however:
/**
* use a fail-early-whitelist-loop (avoiding regular-expressions or length checks on trimmed duplicates)
* using `charCodeAt(i)` (which is faster than `[index]`)
*/
const isOnlySpace = (s, emptyIsTrue=false) => {
let i = String(s || '').length;
if (i === 0) return emptyIsTrue;
while (--i > -1) {
switch (s.charCodeAt(i)) {
case 0x0020: case 0x0009: case 0x000A: case 0x000B: case 0x000C: case 0x000D:
case 0x0085: case 0x00A0: case 0x1680: case 0x180E: case 0x2000: case 0x2001:
case 0x2002: case 0x2003: case 0x2004: case 0x2005: case 0x2006: case 0x2007:
case 0x2008: case 0x2009: case 0x200A: case 0x2028: case 0x2029: case 0x202F:
case 0x205F: case 0x3000:
continue;
default:
return false;
}
}
return true;
};
const tests = ['',' ', '\t\n\r','0',' 0 ','x',' 404 '];
console.log(tests.filter(isOnlySpace)); // fastest
console.log(tests.filter(x => String(x || '').trim().length === 0)); // fast
console.log(tests.filter(x => /^\s*$/.test(x))); // 33% slower
console.log(tests.filter(x => +x === 0 && String(x).indexOf('0') === -1)); // 40 % slower
console.log(tests.filter(x => Number('1 ' + x) === 1)); // 66% slower
Upvotes: 0
Reputation: 337560
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. Here's a working example:
const isWhitespaceString = str => !str.replace(/\s/g, '').length
console.log('isWhitespaceString str1:', isWhitespaceString(' w ')); // false
console.log('isWhitespaceString str2:', isWhitespaceString(' ')); // true
console.log('isWhitespaceString str3:', isWhitespaceString('')); // true
Upvotes: 207
Reputation: 533
You can do this by simply using trim.
var str = " ";
if (str.trim().length == 0)
{
console.log("Your string contains only white spaces.")
console.log(`Your string is >>${str}<<`);
}
Upvotes: 4
Reputation: 9692
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
:
var str1 = ' w ' // false
var str2 = ' ' // true
var str3 = '' // true
const isWhitespaceString = str => !/\S/.test(str)
console.log('isWhitespaceString str1', isWhitespaceString(str1))
console.log('isWhitespaceString str2', isWhitespaceString(str2))
console.log('isWhitespaceString str3', isWhitespaceString(str3))
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.
Upvotes: 76
Reputation: 41
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.
Upvotes: 2
Reputation: 89149
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
}
Upvotes: 45
Reputation: 3264
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'.
Upvotes: -1
Reputation: 3840
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!');
}
Upvotes: 74
Reputation: 111
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");
}
Upvotes: 1
Reputation: 2940
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"
Upvotes: 9