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


当前回答

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

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

其他回答

非常通用的“All-In-One”功能(但不推荐):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。

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

if (!str.length) { ...
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;

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

毫无疑问,快速简单的实现是赢家: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;}

我知道有点过分了。

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