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


当前回答

试试看:

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

其他回答

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' />

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

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

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

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

(/(null|undefined|^$|^\d+$)/).test()

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

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

if (!str.length) { ...

如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}