How to convert a string to Boolean ?
I tried using the constructor Boolean("false")
, but it's always true.
To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.
One of the easiest ways to convert the string to the boolean is to use the comparison ('==') operator with the ternary (? :) operator. However, users can use only the comparison operator also.
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval
... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) { return (val + '').toLowerCase() === 'true'; }
JSPerf
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