JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
试试看:
export const isEmpty = string => (!string || !string.length);
其他回答
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
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(“未定义”));
var s; // undefined
var s = ""; // ""
s.length // 0
JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”
这里有很多有用的信息,但在我看来,其中一个最重要的因素没有得到解决。
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 checkEmpty=string=>(strim.trim()==“”)||!strim.trim();
用法:
checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.
就是这么简单。:)