How to detect string which contains only spaces?

包含一个空格的字符串长度总是等于1:

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

空格是一个字符,所以:

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?

161673 次浏览

为此,可以使用正则表达式删除字符串中的所有空格。如果生成的字符串的长度是 0,那么可以确保原始字符串只包含空格。试试这个:

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

可以通过为 String 创建修剪函数来修剪 String 值。

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

现在它对每个字符串都是可用的,您可以将它用作

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"

最快的解决方案是使用正则表达式原型函数 测试(),并寻找任何不是空格、制表符或换行符的字符 \S:

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

如果您有一个超长的字符串,那么它会产生很大的不同,因为它会在找到一个非空格字符后立即停止处理。

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

String#trim() 删除字符串开始和结束处的空格。如果字符串只包含空格,那么在修剪之后它将是空的,并且空字符串在 JavaScript 中是假的。

如果字符串可能是 nullundefined,我们需要首先检查字符串本身是否为假,然后再进行修剪。

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

这可以通过使用 可选链接操作符来简化。

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

通过创建一个修剪函数来修剪 String 值

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

与 Rory 的回答类似,使用 ECMA5,您现在可以只调用 str.trim().length而不是使用正则表达式。如果结果值为0,那么您知道您有一个只包含空格的字符串。

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

你可以阅读更多关于修剪 给你

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!');
}

这在 Dart not Javascript 中工作。然而,当我搜索如何做到这一点与达特这个问题出现了,所以我认为其他人可能需要达特的答案。

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

为了进一步说明,字符串 ' d '将打印“不是所有的空白空间”,字符串 ' '将打印“所有的空白空间”。

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

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

这将记录为真。

你可以通过简单地使用修剪来做到这一点。

var str = "   ";
if (str.trim().length == 0)
{
console.log("Your string contains only white spaces.")
}

Number进行类型转换可以检测只使用空格的字符串(如果可以排除只包含零的字符串) :

if (+'   ' === 0) console.log('is whitespace');

to make this approach also work for empty- and zerostrings like '0' a truthy numerical prefix could be used:

if (Number('1 0') === 1) console.log('is not whitespace');
if (Number('1 ' + ' \n ') === 1) console.log('is whitespace');

但连铸的成本很高——这就导致了这个晦涩的表达:

String(x || '').indexOf('0') < +x

然而,性能和可读性明智调整的长度仍然胜过正则表达式或强制转换。

const tests = ['',' ', '\t\n\r','0',' 0 ','x',' 404 '];


tests.filter(x => String(x || '').trim().length === 0); // fastest
tests.filter(x => /^\s*$/.test(x)); // 33% slower
tests.filter(x => +x === 0 && String(x).indexOf('0') === -1); // 40 % slower
tests.filter(x => String(x || '').indexOf('0') < +x); // 50% slower
tests.filter(x => Number('1 ' + x) === 1); // 66% slower