Lakshan Perera

jQuery isBlank()

One of my favorite syntactic sugar methods available in Rails is the Object.blank?, which evaluates to true if the given object is false, empty, or a whitespace string. It makes your conditional expressions more readable; avoiding the use of boolean operators.

It would be cool if we can have the same convenience when writing client-side code with JavaScript. Unfortunately, jQuery Core doesn't have such a utility function. Closest you get is with the jQuery.isEmptyObject. It would return true for null, undefined or empty objects and empty arrays; but you can't match whitespace strings with it (which are of course not empty objects).

So, I wrote this small jQuery plugin to check whether the given object is blank:

  $.isBlank = function(obj){
    return(!obj || $.trim(obj) === "");

$.isBlank(" ") //true
$.isBlank("") //true
$.isBlank("\n") //true
$.isBlank("a") //false

$.isBlank(null) //true
$.isBlank(undefined) //true
$.isBlank(false) //true
$.isBlank([]) //true

As shown in the above examples, it would identify any object that evaluates to false (null, undefined, false, []) or a whitespace string as blank.

Update: jtarchie commented on this gist suggesting a alternative method, which would even match the empty objects.