How to check if a variable is null or empty string or all whitespace in JavaScript?

I need to check to see if a variable is null or has all empty spaces or is just blank ("").

I have the following, but it is not working:

var addr;
addr = "  ";

if (!addr) {
    // pull error 
}

If I do the following, it works:

if (addr) {

}​

What I need is something like the C# method String.IsNullOrWhiteSpace(value).


Solution 1:

A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

function isEmptyOrSpaces(str){
    return str === null || str.match(/^ *$/) !== null;
}

...then:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
    // error 
}

* EDIT * Please note that op specifically states:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

Solution 2:

if (addr == null || addr.trim() === ''){
  //...
}

A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).

Solution 3:

You can use if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

Reference: http://api.jquery.com/jQuery.trim/