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


当前回答

Try:

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

其他回答

也可以使用正则表达式:

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

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

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

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);
}

不要假设您检查的变量是字符串。不要假设这个变量有一个长度,那么它就是一个字符串。

问题是:仔细思考你的应用程序必须做什么,可以接受什么。打造强健的体魄。

如果您的方法/函数只处理非空字符串,那么测试参数是否为非空字符串并且不要做一些“技巧”。

作为一个例子,如果你不小心遵循这里的一些建议,就会发生爆炸。


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

所以,我会坚持


if (myVar === '')
  ...

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

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

如果不仅需要检测空字符串,还需要检测空白字符串,我将在Goral的答案中添加:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}