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!
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.