Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String.IsNullOrEmpty Javascript equivalent

I want to try to do string call equivalent to the C# String.IsNullOrEmpty(string) in javascript. I looked online assuming that there was a simple call to make, but I could not find one.

For now I am using a if(string === "" || string === null) statement to cover it, but I would rather use a predefined method (I keep getting some instances that slip by for some reason)

What is the closest javascript (or jquery if then have one) call that would be equal?

like image 795
Soatl Avatar asked Apr 21 '11 16:04

Soatl


2 Answers

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
like image 108
JoJo Avatar answered Sep 21 '22 23:09

JoJo


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.

like image 39
Code Maverick Avatar answered Sep 19 '22 23:09

Code Maverick