JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

为了检查变量是否为false,或者它的长度属性是否等于零(对于字符串,这意味着它为空),我使用:

function isEmpty(str) {
    return (!str || str.length === 0 );
}

(请注意,字符串不是唯一具有长度属性的变量,例如,数组也有它们。)

或者,您可以使用(并非如此)新可选的链接和箭头函数来简化:

const isEmpty = (str) => (!str?.length);

它将检查长度,如果为空值,则返回undefined,而不会抛出错误。在空值的情况下,零是错误的,结果仍然有效。

为了检查变量是否为false,或者字符串是否仅包含空格或为空,我使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

如果需要,您可以像这样对String原型进行猴式修补:

String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used 
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

请注意,monkey修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。

其他回答

Try:

if (str && str.trim().length) {  
    //...
}

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

我宁愿使用非空白测试而不是空白测试

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}

以下正则表达式是另一种解决方案,可用于null、空或未定义的字符串。

(/(null|undefined|^$)/).test(null)

我添加了这个解决方案,因为它可以进一步扩展,以检查空值或某些值,如下所示。下面的正则表达式正在检查字符串是否可以是空的、空的、未定义的或只有整数。

(/(null|undefined|^$|^\d+$)/).test()

检查您是否试图传递未定义的术语也是一个好主意。

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。