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


当前回答

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

其他回答

您也应该经常检查类型,因为JavaScript是一种鸭子类型的语言,所以您可能不知道数据在过程中何时以及如何更改。因此,以下是更好的解决方案:

let undefinedStr;if(!undefinedStr){console.log(“字符串未定义”);}let emptyStr=“”;if(!emptyStr){console.log(“字符串为空”);}让nullStr=null;if(!nullStr){console.log(“字符串为空”);}

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

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

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

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

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

这里有很多有用的信息,但在我看来,其中一个最重要的因素没有得到解决。

null、undefined和“”都是假的。

当计算空字符串时,通常是因为需要用其他东西替换它。

在这种情况下,您可以预期以下行为。

var a = ""
var b = null
var c = undefined

console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"

考虑到这一点,可以返回字符串是否为“”、null或undefined(无效字符串)与有效字符串的方法或函数如下所示:

const validStr = (str) => str ? true : false

validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true

我使用组合,最快的检查是第一个。

function isBlank(pString) {
    if (!pString) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}