Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string to boolean in JavaScript?

People also ask

How do I convert string to boolean?

To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".

How do you convert a string to a boolean in TypeScript?

To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned. Copied!

How do you convert a value to a boolean?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.


Do:

var isTrueSet = (myValue === 'true');

using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types.


Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.


Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".

An invalid json string passed into these functions below WILL throw an exception.


Original answer:

How about?

JSON.parse("True".toLowerCase());

or with jQuery

$.parseJSON("TRUE".toLowerCase());

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
          return false;

        default: 
          return Boolean(string);
    }
}

I think this is much universal:

if (String(a).toLowerCase() == "true") ...

It goes:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false