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


当前回答

也可以使用正则表达式:

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

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

其他回答

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其空性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。

if ((str?.trim()?.length || 0) > 0) {
   // str must not be any of:
   // undefined
   // null
   // ""
   // " " or just whitespace
}

或以函数形式:

const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;

const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;

空字符串,未定义,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
}

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

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

TestMe();

var str = 'hello';

TestMe();

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

前面的所有答案都很好,但这会更好。使用双NOT运算符(!!):

if (!!str) {
    // Some code here
}

或使用类型铸造:

if (Boolean(str)) {
    // Code here
}

两者的功能相同。将变量类型转换为Boolean,其中str是一个变量。

对于null、undefined、0000、“”、false,它返回false。对于除空字符串之外的所有字符串值(包括“0”和“”等字符串),它都返回true