Personally I think it's not good, that your function "hides" invalid values as false
and - depending on your use cases - doesn't return true
for "1"
.
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0"
and "1"
.
(Maybe there is a way to compare only once against "true"
, but I couldn't think of something right now.)