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


当前回答

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

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

其他回答

这是一个错误的值。

第一种解决方案:

const str = "";
return str || "Hello"

第二种解决方案:

const str = "";
return (!!str) || "Hello"; // !!str is Boolean

第三种解决方案:

const str = "";
return (+str) || "Hello"; // !!str is Boolean

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

if (!str.length) { ...

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

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

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

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(“未定义”));