JavaScript中是否存在字符串.Empty,还是只是检查“”?
当前回答
开始于:
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
其他回答
非常通用的“All-In-One”功能(但不推荐):
function is_empty(x)
{
return ( //don't put newline after return
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == 0) // note this line, you might not need this.
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。
function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;
// Now you can check if your string is empty as like
if(plen==0)
{
alert('empty');
}
else
{
alert('you entered something');
}
}
<input type='text' id='pasword' />
这也是检查字段是否为空的通用方法。
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((/^\s*$/).test(str)) { }
检查是否有空字符串或空白字符串。
您也应该经常检查类型,因为JavaScript是一种鸭子类型的语言,所以您可能不知道数据在过程中何时以及如何更改。因此,以下是更好的解决方案:
let undefinedStr;if(!undefinedStr){console.log(“字符串未定义”);}let emptyStr=“”;if(!emptyStr){console.log(“字符串为空”);}让nullStr=null;if(!nullStr){console.log(“字符串为空”);}