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


当前回答

检查是否为字符串类型,如果不为空:

const isNonEmptyString = (val) => typeof val === 'string' && !!val

其他回答

开始于:

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

我没有注意到一个考虑到字符串中可能存在空字符的答案。例如,如果我们有一个空字符串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其空性,可以执行以下操作:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它在空字符串和空字符串上工作,所有字符串都可以访问它。此外,它还可以扩展为包含其他JavaScript空字符或空白字符(即非分隔空格、字节顺序标记、行/段落分隔符等)。

我通常使用以下内容:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

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

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

试试这个

str.value.length == 0