JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
var x =" ";
var patt = /^\s*$/g;
isBlank = patt.test(x);
alert(isBlank); // Is it blank or not??
x = x.replace(/\s*/g, ""); // Another way of replacing blanks with ""
if (x===""){
alert("ya it is blank")
}
其他回答
如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
最接近str.Empty(前提是str是String)的是:
if (!str.length) { ...
忽略空白字符串,您可以使用它来检查null、空和undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
它简明扼要,适用于未定义的财产,尽管它不是最可读的。
Try:
if (str && str.trim().length) {
//...
}
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。