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


当前回答

也可以使用正则表达式:

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

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

其他回答

所有这些答案都很好。

但我不能确定变量是一个字符串,不只包含空格(这对我来说很重要),并且可以包含“0”(字符串)。

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle上的示例。

另一种方式,但我相信bdukes的答案是最好的。

var myString = 'hello'; 
if(myString.charAt(0)){
    alert('no empty');
}
alert('empty');

试试看:

export const isEmpty = string => (!string || !string.length);

Try:

if (str && str.trim().length) {  
    //...
}

没有isEmpty()方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

当测试未定义或为空时,需要进行类型检查以避免运行时错误。