How to check empty/undefined/null string in JavaSc

2018-12-31 03:34发布

I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

30条回答
若你有天会懂
2楼-- · 2018-12-31 04:07

Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.

The thing is: think carefully about what your app must do and can accept. Build something robust.

If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.

As an example of something that will explode if you follow some advices here not carefully.


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'

So, I'd stick with


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

查看更多
春风洒进眼中
3楼-- · 2018-12-31 04:08

Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:

!/\S/.test(string); // Returns true if blank.
查看更多
长期被迫恋爱
4楼-- · 2018-12-31 04:08

All these answers are nice.

But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).

My version:

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

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

Sample on jsfiddle.

查看更多
步步皆殇っ
5楼-- · 2018-12-31 04:09

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

EDIT: per comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

查看更多
笑指拈花
6楼-- · 2018-12-31 04:13

I use a combination, fastest checks are first.

function isBlank(pString){
    if (!pString || pString.length == 0) {
        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);
}
查看更多
妖精总统
7楼-- · 2018-12-31 04:14

you could also go with regexps:

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

Checks for strings that are either empty or filled with whitespace.

查看更多
登录 后发表回答