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


当前回答

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

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

TestMe();

var str = 'hello';

TestMe();

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

其他回答

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

if (!str.length) { ...

空字符串,未定义,null。。。

检查真实值:

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}

要检查错误值,请执行以下操作:

if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}

空字符串(仅限!)

要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:

if (strValue === "") {
    // strValue was empty string
}

要严格检查非空字符串,请使用!==操作员:

if (strValue !== "") {
    // strValue was not an empty string
}

检查是否为字符串类型,如果不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val

如果您需要确保字符串不只是一堆空格(我假设这是为了表单验证),则需要对空格进行替换。

if(str.replace(/\s/g,"") == ""){
}

试试这个

str.value.length == 0