JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
我通常使用以下内容:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
其他回答
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
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")
}
您可以使用lodash:_.isEmpty(值)。
它涵盖了许多情况,如{}、“”、null、undefined等。
但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。
试试看:
export const isEmpty = string => (!string || !string.length);
另一种方式,但我相信bdukes的答案是最好的。
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');