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;
You can create your own method Equivalent to
String.IsNullOrWhiteSpace(value)
function IsNullOrWhiteSpace( value) {
if (value== null) return true;
return value.replace(/\s/g, '').length == 0;
}
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)
.
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* @param {any} str string to be evaluated
* @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
function isEmptyOrSpaces(str){
return str === null || str.match(/^[\s\n\r]*$/) !== null;
}
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.
isEmptyOrSpaces(str){
return !str || str.trim() === '';
}