Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  113] [ 6]  / answers: 1 / hits: 169024  / 12 Years ago, thu, april 19, 2012, 12:00:00

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).


More From » jquery

 Answers
32

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.


[#86129] Wednesday, April 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
tylerdamiena questions
;