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


当前回答

Try:

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

其他回答

有很多答案,还有很多不同的可能性!

毫无疑问,快速简单的实现是赢家:if(!str.length){…}

然而,还有许多其他例子。我建议,最好的功能方法是:

函数为空(str){if(str类型==‘undefined‘||!str | | str.length==0 | | str==“”||!/[^\s]/.test(str)||/^\s*$/.test(str)|| str.replace(/\s/g,“”)==“)返回true;其他的return false;}

我知道有点过分了。

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

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

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

(/(null|undefined|^$|^\d+$)/).test()
function tell()
{
    var pass = document.getElementById('pasword').value;
    var plen = pass.length;

    // Now you can check if your string is empty as like
    if(plen==0)
    {
        alert('empty');
    }
    else
    {
        alert('you entered something');
    }
}

<input type='text' id='pasword' />

这也是检查字段是否为空的通用方法。

我使用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

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

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