Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Checks whether the given string (or object) is blank
(function($){
$.isBlank = function(string){
return(!string || $.trim(string) === "");
};
})(jQuery);
$.isBlank(" ") //true
$.isBlank("") //true
$.isBlank("\n") //true
$.isBlank("a") //false
$.isBlank(null) //true
$.isBlank(undefined) //true
$.isBlank([]) //true
@jtarchie

This comment has been minimized.

Copy link

@jtarchie jtarchie commented Jan 7, 2011

$.isBlank([]) // throws an excption

It appears that you are having unexpected behavior from ![](actually returns false).

@jtarchie

This comment has been minimized.

Copy link

@jtarchie jtarchie commented Jan 8, 2011

    $.isBlank = function(object) {
        return (
            ($.isPlainObject(object) && $.isEmptyObject(object)) ||
            ($.isArray(object) && object.length == 0) ||
            (typeof(object) == "string" && $.trim(object) === "") ||
            (!object)
        );
    };

This fixes the issue with empty array, and added empty hashes.

@yckart

This comment has been minimized.

Copy link

@yckart yckart commented Feb 27, 2013

jQuery.isBlank = function (obj) {
    if (!obj || $.trim(obj) === "") return true;
    if (obj.length && obj.length > 0) return false;

    for (var prop in obj) if (obj[prop]) return false;
    return true;
};
console.log(
    $.isBlank(0), // true
    $.isBlank(""), // true
    $.isBlank(null), // true
    $.isBlank(false), // true
    $.isBlank(undefined), // true

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

    $.isBlank({}), // true
    $.isBlank({foo: 0}), // true
    $.isBlank({foo: null}), // true
    $.isBlank({foo: false}), // true
    $.isBlank({foo: undefined}), // true

    $.isBlank("Hello"), // false
    $.isBlank([1,2,3]), // false
    $.isBlank({foo: 1}), // false
    $.isBlank({foo: 3, bar: [1,2,3]}), // false

    "incorrect:",
    $.isBlank(1), // true
    $.isBlank(true), // true

    $.isBlank([0]), // false
    $.isBlank([false]), // false
    $.isBlank("0"), // false
    $.isBlank(["0"]), // false
    $.isBlank({foo: "0"}) // false
);
@unitario

This comment has been minimized.

Copy link

@unitario unitario commented Apr 23, 2017

@yckart Hey, here form the future to tell you that for (var prop in obj) if (obj[prop]) return false will return false for additional properties on the prototype chain and this might not be the desired behavior; it would be wise to use for (var prop in obj) if (obj.hasOwnProperty(key) && obj[key]) return false. Also jQuery, is this thing still around?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.