如何在JavaScript中检查空/未定义/空字符串?

3976
在 JavaScript 中是否有类似于 string.Empty 的方法,或者只需要检查 "" 是否为空?

5
仅供参考,我认为String类最有用的API在Mozillajavascript kit上。elated.com提供了关于String所有属性、方法的教程...请注意:Mozilla链接已更新为https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String。 - Gene T
2
如果需求明确指定,那将会非常有帮助。isEmpty 应该在什么情况下返回 true?检查 "" 暗示它只应在值为字符串类型且长度为 0 时返回 true。这里的许多答案都假设它也应该对某些或所有 falsy 值返回 true。 - RobG
str.length > -1 - Omar bakhsh
我完全同意@RobG的观点,这个问题定义得很糟糕。你为什么会认为nullundefined是空的呢?一个空字符串就是一个空字符串,它不是nullundefined - Flimm
@GeneT的链接已经失效,这里提供Mozilla参考文档的更新链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String - randy
显示剩余2条评论
54个回答

4

以下正则表达式是另一种解决方法,可用于空、空字符串或未定义的字符串。

(/(null|undefined|^$)/).test(null)

我添加了这个解决方案,因为它可以进一步扩展以检查空值或一些像下面这样的值。以下正则表达式正在检查字符串是否为空、null、undefined或仅包含整数。

(/(null|undefined|^$|^\d+$)/).test()

2
一个主要的缺陷:这个正则表达式匹配了字符串字面量"null"。(/(null|undefined|^$)/).test("null") - sean

4
Underscore.js JavaScript 库(http://underscorejs.org/)提供了一个非常有用的 _.isEmpty() 函数,用于检查空字符串和其他空对象。
参考文献:http://underscorejs.org/#isEmpty

isEmpty _.isEmpty(object)
如果枚举对象不包含值(没有可枚举的自有属性),则返回 true。对于字符串和类数组对象,_.isEmpty 检查长度属性是否为 0。

_.isEmpty([1, 2, 3]);
=> false

_.isEmpty({});
=> true

其他非常有用的 Underscore.js 函数包括:

4

这是一个假值

第一个解决方案:

const str = "";
return str || "Hello"

第二个解决方案:
const str = "";
return (!!str) || "Hello"; // !!str is Boolean

第三种解决方案:
const str = "";
return (+str) || "Hello"; // !!str is Boolean

1
第三种解决方案基本上是错误的,当输入不是数字时,解析结果将为 NaN,这也是“假值”。 - devildelta

4

isBlank 函数的最终和最短变体:

/**
 * Will return:
 * False for: for all strings with chars
 * True for: false, null, undefined, 0, 0.0, "", " ".
 *
 * @param str
 * @returns {boolean}
 */
function isBlank(str){
    return (!!!str || /^\s*$/.test(str));
}

// tests
console.log("isBlank TRUE variants:");
console.log(isBlank(false));
console.log(isBlank(undefined));
console.log(isBlank(null));
console.log(isBlank(0));
console.log(isBlank(0.0));
console.log(isBlank(""));
console.log(isBlank(" "));

console.log("isBlank FALSE variants:");
console.log(isBlank("0"));
console.log(isBlank("0.0"));
console.log(isBlank(" 0"));
console.log(isBlank("0 "));
console.log(isBlank("Test string"));
console.log(isBlank("true"));
console.log(isBlank("false"));
console.log(isBlank("null"));
console.log(isBlank("undefined"));


4

我更喜欢使用“非空测试”而不是“空白测试”

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}

3
在函数名中加入否定词是一个不好的做法。你的代码本身很好,但函数应该被称为类似hasValue()这样的名称。为什么?当你看到像这样的代码:"if (!isNotBlank(str))"时会发生什么... 它并不立即清楚意图应该是什么。对于这个简单的例子可能看起来并不相关,但在函数名中添加否定词总是一个不好的做法。 - Mike Viens
IsNotBlank是StringUtils中的一个标准函数,也是非常受欢迎的函数。 https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNotBlank-java.lang.CharSequence- - Mubashar
它还提供了IsBlank来避免双重否定。我认为函数名应该反映它们执行的功能,这样当开发者在同一类中看到isBlank和IsNotBlank函数时,就更容易理解。 - Mubashar

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

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

3

还有一个好主意是检查您是否尝试传递未定义的术语。

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

我经常遇到这样的情况:当一个对象实例的字符串属性不为空时,我想要做一些事情。问题是,该属性并不总是存在。


2
另一种方法,但我认为bdukes的答案是最好的。
var myString = 'hello'; 
if(myString.charAt(0)){
    alert('no empty');
}
alert('empty');

1

0

这里是我用于处理此问题的一些自定义函数。以及代码运行示例。

const v1 = 0
const v2 = '4'
const v2e = undefined
const v2e2 = null
const v3 = [1, 2, 3, 4]
const v3e = []
const v4 = true
const v4e = false
const v5 = {
  test: 'value'
}
const v5e = {}
const v6 = 'NotEmpty'
const v6e = ''

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n)
}

function isEmpty(v, zeroIsEmpty = false) {
  /**
   * When doing a typeof check, null will always return "object" so we filter that out first
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null
   */
  if (v === null) {
    return true
  }

  if (v === true) {
    return false
  }

  if (typeof v === 'object') {
    return !Object.keys(v).length
  }

  if (isNumeric(v)) {
    return zeroIsEmpty ? parseFloat(v) === 0 : false
  }

  return !v || !v.length || v.length < 1
}

console.log(isEmpty(v1), isEmpty(v1, true))
console.log(isEmpty(v2), isEmpty(v2e), isEmpty(v2e))
console.log(isEmpty(v3), isEmpty(v3e))
console.log(isEmpty(v4), isEmpty(v4e))
console.log(isEmpty(v5), isEmpty(v5e))
console.log(isEmpty(v6), isEmpty(v6e))

另外作为参考,这里是Lodash isEmpty的源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接