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


当前回答

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

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

其他回答

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

这是一个错误的值。

第一种解决方案:

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

第二种解决方案:

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

第三种解决方案:

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

您可以使用lodash:_.isEmpty(值)。

它涵盖了许多情况,如{}、“”、null、undefined等。

但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。

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;

开始于:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:

return (!value || value == undefined || value == "");

但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:

return (!value || value == undefined);

和undefined为true,因此不需要检查。因此,我们有:

return (!value);

我们不需要括号:

return !value