To find out a string is null or just contents white space, you can use a similar method: string. IsNullOrWhiteSpace(), which can pretty much be used in the same way as the string. IsNullOrEmpty.
Use the === Operator to Check if the String Is Empty in JavaScript. We can use the strict equality operator ( === ) to check whether a string is empty or not. The comparison data==="" will only return true if the data type of the value is a string, and it is also empty; otherwise, return false .
Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.
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/
Old question, but I think it deservers a simpler answer.
You can simply do:
var addr = " ";
if (addr && addr.trim()) {
console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With