JavaScript: Parsing a string Boolean value?

AgileMeansDoAsLittleAsPossible picture AgileMeansDoAsLittleAsPossible · Mar 7, 2011 · Viewed 161.7k times · Source

JavaScript has parseInt() and parseFloat(), but there's no parseBool or parseBoolean method in the global scope, as far as I'm aware.

I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean.

Here's my implementation:

function parseBool(value) {
    return (typeof value === "undefined") ? 
           false : 
           // trim using jQuery.trim()'s source 
           value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}

Is this a good function? Please give me your feedback.

Thanks!

Answer

RGB picture RGB · Jan 18, 2012

I would be inclined to do a one liner with a ternary if.

var bool_value = value == "true" ? true : false

Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

var bool_value = value == 'true';

This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.