How to check if a variable is null or empty string or all whitespace in JavaScript?
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.
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)
.
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/