Skip to main content

JavaScript function to parse a Boolean like value.

/**
 * Parses value to a boolean.
 *
 * http://stackoverflow.com/a/22236564
 *
 * @param {Mixed} val
 * @return {Boolean} true/false
 */
var parseBool = function (val) {
    if (val === null) {
        return false;
    }

    if (typeof val === 'boolean') {
        if (val === true) {
            return true;
        }
        return false;
    }

    if (typeof val === 'string') {
        if (val === '') {
            return false;
        }

        val = val.replace(/^\s+|\s+$/g, '');
        if (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes') {
            return true;
        }

        val = val.replace(/,/g, '.');
        val = val.replace(/^\s*\-\s*/g, '-');
    }

    if (!isNaN(val)) {
        return (parseFloat(val) !== 0);
    }

    return false;
};