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!
toString(boolean b): This method works same as String. valueOf() method. It belongs to the Boolean class and converts the specified boolean to String. If the passes boolean value is true then the returned string would be having “true” value, similarly for false the returned string would be having “false” value.
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned.
Primitive data types in Javascript like Number, String, Boolean always pass by value whereas Objects are pass by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With