JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
Try:
if (str && str.trim().length) {
//...
}
其他回答
空字符串,未定义,null。。。
检查真实值:
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
要检查错误值,请执行以下操作:
if (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
空字符串(仅限!)
要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:
if (strValue === "") {
// strValue was empty string
}
要严格检查非空字符串,请使用!==操作员:
if (strValue !== "") {
// strValue was not an empty string
}
也可以使用正则表达式:
if((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
试试看:
export const isEmpty = string => (!string || !string.length);
您可以使用lodash:_.isEmpty(值)。
它涵盖了许多情况,如{}、“”、null、undefined等。
但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。
以下正则表达式是另一种解决方案,可用于null、空或未定义的字符串。
(/(null|undefined|^$)/).test(null)
我添加了这个解决方案,因为它可以进一步扩展,以检查空值或某些值,如下所示。下面的正则表达式正在检查字符串是否可以是空的、空的、未定义的或只有整数。
(/(null|undefined|^$|^\d+$)/).test()