Generic Function to Check Empty\Null string in JavaScript

A generic function in JavaScript similar to"String.IsNullOrEmpty" of C#, to check whether the specified string is null or empty.

How often we check a string for Null, Undefined & empty string in a JavaScript code. Here is my very basic method StringHasValue to check if a string is either null, undefined or if it’s an empty string (String to be checked may contain white-spaces, that is also considered). Although it’s a very basic method but definitely it is going to save our time, less coding efforts & it will be less error prone.
  1. var StringHasValue = function(strValue){  
  2.    if($.trim(strValue) != "" && $.trim(strValue) != null && $.trim(strValue) != undefined)  
  3.    return true;  
  4.    else  
  5.    return false;  
  6. };  
This function return boolean, true if string has some value & false if its null or an empty string.
We can simply use this function in our entire appliication like this:
  1. if(StringHasValue($("#ddlCountries").val())  
  2. alert("Yes");  
  3. else  
  4. alert("No");  
Ebook Download
View all
Learn
View all