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


当前回答

我使用组合,最快的检查是第一个。

function isBlank(pString) {
    if (!pString) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}

其他回答

我使用:

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

忽略空白字符串,您可以使用它来检查null、空和undefined:

var obj = {};
(!!obj.str) // Returns false

obj.str = "";
(!!obj.str) // Returns false

obj.str = null;
(!!obj.str) // Returns false

它简明扼要,适用于未定义的财产,尽管它不是最可读的。

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' />

这也是检查字段是否为空的通用方法。

前面的所有答案都很好,但这会更好。使用双NOT运算符(!!):

if (!!str) {
    // Some code here
}

或使用类型铸造:

if (Boolean(str)) {
    // Code here
}

两者的功能相同。将变量类型转换为Boolean,其中str是一个变量。

对于null、undefined、0000、“”、false,它返回false。对于除空字符串之外的所有字符串值(包括“0”和“”等字符串),它都返回true

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。