Convert string to Boolean in javascript

110,995

Solution 1

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";

Solution 2

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

Solution 3

you can also use JSON.parse() function

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

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

Solution 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

Solution 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.

Share:
110,995
user137348
Author by

user137348

Updated on November 08, 2020

Comments

  • user137348
    user137348 over 3 years

    How to convert a string to Boolean ?

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