How to convert a string to boolean?

Asked

Viewed 2,812 times

2

In Javascript, when running

Boolean('false')

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

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

  • What kind of content do you want to convert? Boolean() works well and is semantically correct.

  • Yes, in my view this is the best way: Boolean(string).

  • 2

    @vnbrs you want to Boolean('false') give false? want to know how to detect false within a string? is that the question?

  • var convertido = 'false' == 'true';

  • 2

    But you are very confused. You yourself say that any empty string is considered true, but claims that Boolean("false") would be expected false. That doesn’t make sense.

3 answers

2


Compare the string you want to validate with true:

var texto = 'false';
var valBool = texto.toLowerCase() == 'true';

1

var varbool = Boolean('false'=='true');
alert(varbool);

0

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.

  • The answer https://answall.com/a/235274/80474 is much simpler. Both the Eval and the method includes add an expendable overhead to the code (in addition to the includes have a very limited usage range as expressed here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/contains)

  • 1

    I wasn’t clear when I said includes was just a way of exemplifying that he could do a check and that the Eval was not recommended, but is it always worth the knowledge or you who didn’t read everything I wrote? And yet, I made a point of saying that the example using comparison had already been cited before.

  • @stefanosanders Wanted to withdraw the down vote, how do I do? You need to edit your answer, that’s it?

  • Boy, I don’t know, I guess in that case neither eval nor includes will solve rs :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.