Introduction

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 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 returns boolean, true if the string has some value & false if it's null or an empty string.
We can simply use this function in our entire application like this:
  1. if(StringHasValue($("#ddlCountries").val())
  2. alert("Yes");
  3. else
  4. alert("No");