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


当前回答

没有isEmpty()方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

当测试未定义或为空时,需要进行类型检查以避免运行时错误。

其他回答

试试看:

export const isEmpty = string => (!string || !string.length);

您可以很容易地将它添加到JavaScript中的原生String对象中,并反复使用它。。。如果您想检查“”空字符串,下面的代码可以为您完成这项工作:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
  return !(!!this.length);
}

否则,如果您想同时检查“”空字符串和“”带空格,可以通过添加trim()来完成,类似于下面的代码:

String.prototype.isEmpty = String.prototype.isEmpty || function() {
   return !(!!this.trim().length);
}

你可以这样称呼它:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false

使用空合并运算符修剪空格:

if (!str?.trim()) {
  // do something...
}

检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}

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

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空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。