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


当前回答

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

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
}

我使用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

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

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

为了检查变量是否为false,或者它的长度属性是否等于零(对于字符串,这意味着它为空),我使用:

function isEmpty(str) {
    return (!str || str.length === 0 );
}

(请注意,字符串不是唯一具有长度属性的变量,例如,数组也有它们。)

或者,您可以使用(并非如此)新可选的链接和箭头函数来简化:

const isEmpty = (str) => (!str?.length);

它将检查长度,如果为空值,则返回undefined,而不会抛出错误。在空值的情况下,零是错误的,结果仍然有效。

为了检查变量是否为false,或者字符串是否仅包含空格或为空,我使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

如果需要,您可以像这样对String原型进行猴式修补:

String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used 
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

请注意,monkey修补内置类型是有争议的,因为无论出于什么原因,它都会破坏依赖于内置类型现有结构的代码。

试试这个

str.value.length == 0