Possible but not recommended
If you need to convert directly can use the function eval()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval.
In your case I could do:
const parseBool = value => eval(value)
This code is very insecure, because I did no checking to know value
is true or false (like string), but like this parsedValue
will have a boolean value. There are security problems involved, because Val, depending on the form and purpose with which it is used, can open gaps to code Injection in its application.
Recommendable
I believe that the best solution is to use comparison as already mentioned:
const parseBool = value =>
['true', 'false'].includes(value) ? value === true : null
This example accompanies a small check just to illustrate the fact that you can return null
or any other value to identify that the value passed is invalid or something like that, but is not required.
What kind of content do you want to convert?
Boolean()
works well and is semantically correct.– Sergio
Yes, in my view this is the best way:
Boolean(string)
.– Woss
@vnbrs you want to
Boolean('false')
givefalse
? want to know how to detectfalse
within a string? is that the question?– Sergio
var convertido = 'false' == 'true';
– Jéf Bueno
But you are very confused. You yourself say that any empty string is considered
true
, but claims thatBoolean("false")
would be expectedfalse
. That doesn’t make sense.– Woss