[Solved-5 Solutions] Check for an empty string in javascript - javascript tutorial



Problem:

Check for an empty string in javascript

Solution 1:

If we need to check whether there's any value, we can do

if (strValue) 
{
    //....
}

If we want to check specifically for an empty string over null, We would think checking against "" is our best bet, using the === operator.

if (strValue === "") 
{
    //...
}

Solution 2:

To check whether a string is empty, null or undefined we can use:

function isEmpty(str)
{
    return (!str || 0 === str.length);
}

To check whether a string is blank, null or undefined we can use:

function isBlank(str) 
{
    return (!str || /^\s*$/.test(str));
}

To check whether a string is blank or contains only white-space:

String.prototype.isEmpty = function() 
{
    return (this.length === 0 || !this.trim());
};

Solution 3:

We can use !!(not not) operator.

if(!!str)
{
      //......
}

or use type casting:

if(Boolean(str))
{
    //......
}
  • Both do the same function, type cast the variable to boolean, where str is a variable.
  • Returns false for null,undefined,0,000,"",false.
  • Returns true for string "0" and whitespace " ".

Solution 4:

If we want to ensure that the string is not just a group of empty spaces (In our imagining this is for form validation) we need to do a replace on the spaces.

if(str.replace(/\s/g,"") == "")
{
    //......
}

Solution 5:

In this solution to check for an str.Empty,

if (!str.length) 
 { 
   //...
 }


Related Searches to javascript tutorial - Check for an empty string in javascript