How to convert a string to boolean? [closed]

2

In JavaScript, when running

Boolean('false')

The returned value is true and the expected value was false , since strings with any non-empty content when converted to boolean return true and empty false .

What is the best way to convert a string to a boolean in JavaScript?

    
asked by anonymous 06.09.2017 / 15:22

3 answers

2

Compare the string that you want to validate with true :

var texto = 'false';
var valBool = texto.toLowerCase() == 'true';
    
06.09.2017 / 15:24
1

var varbool = Boolean('false'=='true');
alert(varbool);
    
06.09.2017 / 15:32
0

Possible but not recommended

If you need to convert directly you can use the eval() function: link .

In your case you could do:

const parseBool = value => eval(value)

This code is very insecure, as I did no check to know value is true or false (as string), but so parsedValue will have a boolean value. There are security issues involved, because eval, depending on the form and purpose with which it is used, can open gaps for code injection . in your application.

Recommended

I think the best solution is to use comparison as already mentioned:

const parseBool = value => 
      ['true', 'false'].includes(value) ? value === true : null

This example comes with a small check only to illustrate the fact that you can return null or any other value to identify that the passed value is invalid or something, but it is not required.

    
06.09.2017 / 15:54