C# String.IsNullOrEmpty Javascript equivalent

Solution 1:

You're overthinking. Null and empty string are both falsey values in JavaScript.

if(!theString) {
 alert("the string is null or empty");
}

Falsey:

  • false
  • null
  • undefined
  • The empty string ''
  • The number 0
  • The number NaN

Solution 2:

If, for whatever reason, you wanted to test only null and empty, you could do:

function isNullOrEmpty( s ) 
{
    return ( s == null || s === "" );
}

Note: This will also catch undefined as @Raynos mentioned in the comments.

Solution 3:

if (!string) {
  // is emtpy
}

What is the best way to test for an empty string with jquery-out-of-the-box?

Solution 4:

If you know that string is not numeric, this will work:

if (!string) {
  .
  .
  .