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


当前回答

最接近str.Empty(前提是str是String)的是:

if (!str.length) { ...

其他回答

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

尝试以下代码:

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

您可以使用typeof运算符和length方法检查这一点。

const isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0

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

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

TestMe();

var str = 'hello';

TestMe();

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

开始于:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:

return (!value || value == undefined || value == "");

但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:

return (!value || value == undefined);

和undefined为true,因此不需要检查。因此,我们有:

return (!value);

我们不需要括号:

return !value