JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
if ((str?.trim()?.length || 0) > 0) {
// str must not be any of:
// undefined
// null
// ""
// " " or just whitespace
}
或以函数形式:
const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;
const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;
其他回答
我通常使用以下内容:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
尝试以下代码:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
忽略空白字符串,您可以使用它来检查null、空和undefined:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
它简明扼要,适用于未定义的财产,尽管它不是最可读的。
检查var a;存在删除值中的假空格,然后测试是否为空如果((a)&&(a.trim()!=“”)){//如果变量a不为空,请执行以下操作}
另一种方式,但我相信bdukes的答案是最好的。
var myString = 'hello';
if(myString.charAt(0)){
alert('no empty');
}
alert('empty');