37

How to convert a string to Boolean ?

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

1

13 Answers 13

87

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";
Sign up to request clarification or add additional context in comments.

8 Comments

Reading this in 2014, and still amazed by the simplicity of this solution.
perhaps var myBool = myString.toLowerCase() == "true" will be better
THIS DOES NOT WORK! Just initialize myString = true; and you will see that myBool returns false!!!
@EugenMihailescu true is not a string value, which is what the question is asking about.
@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";
|
20

you can also use JSON.parse() function

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

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

2 Comments

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.
Also it can misinterpret strings as being numbers. typeof JSON.parse("10") === 'number'
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

Comments

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.

1 Comment

Boolean(variable); Did the trick for me :)
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

Comments

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!

4 Comments

Doing myString = true is different from what the OP asked, he asked for a string to boolean conversion...
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.
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: 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.
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.

Comments

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.

Comments

0

These lines give the following output:

Boolean(1).toString(); // true
Boolean(0).toString(); // false

Comments

-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

Comments

-2

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.

Comments

-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());

1 Comment

Boolean("false") is actually true
-5

You can try this:

var myBoolean = Boolean.parse(boolString);

2 Comments

TypeError: Object function Boolean() { [native code] } has no method 'parse'
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.