36

How to convert a string to Boolean ?

I tried using the constructor Boolean("false"), but it's always true.

franzlorenzon
  • 5,845
  • 6
  • 36
  • 58
user137348
  • 10,166
  • 18
  • 69
  • 89
  • 3
    have a look at this, similar previous question with answers [Other stack overflow question](http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – Steve Dec 03 '10 at 10:24

13 Answers13

85

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";
Aistina
  • 12,435
  • 13
  • 69
  • 89
  • 6
    Reading this in 2014, and still amazed by the simplicity of this solution. – sargas Apr 03 '14 at 15:56
  • 1
    perhaps var myBool = myString.toLowerCase() == "true" will be better – Stupidfrog Jan 08 '15 at 03:09
  • 2
    THIS DOES NOT WORK! Just initialize myString = true; and you will see that myBool returns false!!! – Eugen Mihailescu Apr 30 '15 at 09:51
  • 6
    @EugenMihailescu true is not a string value, which is what the question is asking about. – Aistina Apr 30 '15 at 09:52
  • 1
    @EugenMihailescu right. I'm just pointing out that in a way your comment was off topic. The question and answer are about converting a string value to a Boolean whereas in your case no conversion is necessary. However if you want to support both the answer could be easily amended to: var myBool = myString === true || myString === "true"; – Aistina Apr 30 '15 at 10:09
  • @Aistina: .. or with fewer opcodes/shorter/faster: String(myString)=='true' – Eugen Mihailescu Apr 30 '15 at 10:24
  • 1
    @EugenMihailescu doesn't look like that's faster: http://jsperf.com/string-to-boolean-test – Aistina Apr 30 '15 at 11:53
  • It's 2021 and this solution is still practical – Tim Bogdanov Sep 03 '21 at 18:10
17

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

enter image description here

Jeff Voss
  • 3,637
  • 8
  • 46
  • 71
17

you can also use JSON.parse() function

JSON.parse("true") returns true (Boolean)

JSON.parse("false") return false (Boolean)

  • 8
    If anyone implements this as a solution, keep in mind that if you reference a property of `undefined` that will be cause a `SyntaxError: Unexpected token u in JSON at position 0`. Be sure to check that the value can be parsed first. – justinpage Feb 14 '18 at 22:33
  • Also it can misinterpret strings as being numbers. `typeof JSON.parse("10") === 'number'` – MrYellow Apr 19 '21 at 00:49
5

Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.

var variable = some value; Boolean(variable);

If my variable have some value then it will return true else return false You can't use Boolean as you think.

4

trick string to boolean conversion in javascript. e.g.

var bool= "true";
console.log(bool==true) //false

var bool_con = JSON.parse(bool);

console.log(bool_con==true) //true
Sandeep
  • 1,461
  • 13
  • 26
3

I am still amazed how people vote blindly for solutions that won't work, like:

var myBool = myString == "true";

The above is so BUGGY!!!

Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!

Alternative

var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!

will always evaluate right!

Eugen Mihailescu
  • 3,553
  • 2
  • 32
  • 29
  • 5
    Doing myString = true is different from what the OP asked, he asked for a string to boolean conversion... – Stranded Kid Jun 08 '15 at 12:40
  • It doesn't matter! A good programmer will always provide a code that covers as much as possible and in the same time keep the code as simple as possible. Don't tell me "your comment is off the topic" because at the end of the day what the reader wants is the best of the best. This is not a beauty contest nor a right vs wrong contest. This is a forum where programmers share the best solution such that everyone wins. Otherwise all this is pointless/useless. – Eugen Mihailescu Jun 08 '15 at 13:14
  • 1
    Unbelievable how you neglected lots of potential pitfalls in your solution. X could be 5 or "5" or like you yourself suggested "whatever". All of these will evaluate to false which is clearly not correct. You as a good programmer that always tries to far exceed the requested should know better than to post such buggy code on this forum. – Xatian Aug 17 '16 at 08:38
  • @Xatian: I don't really understand what you mean by "lot of potential pitfalls". Your named example (X could be 5 or "5") is evaluated to boolean false because 5 or "5" is not a valid the boolean constant, it is an integer. So the proposed alternative works. Any suggestion/counter-example that would improve the suggested alternative is welcome. – Eugen Mihailescu Sep 16 '16 at 12:36
1

Depends on what you see as false in a string.

Empty string, the word false, 0, should all those be false or is only empty false or only the word false.

You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.

David Mårtensson
  • 7,550
  • 4
  • 31
  • 47
1

I believe the following code will do the work.

function isBoolean(foo) {
    if((foo + "") == 'true' || (foo + "") == 'false') {
        foo = (foo + "") == 'true';
    } else { 
        console.log("The variable does not have a boolean value.");
        return;
    }
    return foo;
}

Explaining the code:

foo + ""

converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.

(foo + "") == 'true'

This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.

(foo + "") == 'true' || (foo + "") == 'false'

Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.

In the 3rd line, the value of 'foo' is finally "converted" to boolean.

Wesley Gonçalves
  • 1,985
  • 2
  • 19
  • 22
0

These lines give the following output:

Boolean(1).toString(); // true
Boolean(0).toString(); // false
Johan B
  • 890
  • 3
  • 23
  • 39
Felipe Marques
  • 131
  • 1
  • 3
-1

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.
Lifu Huang
  • 11,930
  • 14
  • 55
  • 77
Malhaar Punjabi
  • 735
  • 7
  • 9
-2
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')

will not work because any non-empty string is true

javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')

works because compared with string represenation

Free Consulting
  • 4,300
  • 1
  • 29
  • 50
-5

You can try this:

var myBoolean = Boolean.parse(boolString);

Serge Wazuki
  • 31
  • 1
  • 5
  • 1
    TypeError: Object function Boolean() { [native code] } has no method 'parse' – Michael Hart Jun 13 '12 at 02:26
  • It doesn't look like `Boolean.parse()` is widely available, but it's definitely in current release versions of Chrome (I'm using v21) and it works as expected. – mbeasley Aug 20 '12 at 12:42
-5

See this question for reference:

How can I convert a string to boolean in JavaScript?

There are a few ways:

// Watch case sensitivity!
var boolVal = (string == "true");

or

var boolVal = Boolean("false");

or

String.prototype.bool = function() {
    return (/^true$/i).test(this);
};
alert("true".bool());
Community
  • 1
  • 1
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456