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


当前回答

Try:

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

其他回答

我通常用这样的东西,

if (!str.length) {
    // Do something
}

非常通用的“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))
    );
}

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

isBlank函数的最终和最短变体:

/***将返回:*False for:对于所有带字符的字符串*True for:false,null,undefined,0,0.0,“”,“”。**@param字符串*@return{boolean}*/函数isBlank(str){return(!!!str||/^\s*$/.test(str));}//测试console.log(“isBlank TRUE变量:”);console.log(isBlank(false));console.log(isBlank(未定义));console.log(isBlank(null));console.log(isBlank(0));console.log(isBlank(0.0));console.log(isBlank(“”));console.log(isBlank(“”));console.log(“isBlank FALSE变量:”);console.log(isBlank(“0”));console.log(isBlank(“0.0”));console.log(isBlank(“0”));console.log(isBlank(“0”));console.log(isBlank(“测试字符串”));console.log(isBlank(“true”));console.log(isBlank(“false”));console.log(isBlank(“null”));console.log(isBlank(“未定义”));

Try:

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

检查是否为字符串类型,如果不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val