How can I convert a string to boolean in JavaScript?

ID : 178

viewed : 52

Tags : javascriptboolean-expressionboolean-operationsstring-conversionjavascript

Top 5 Answer for How can I convert a string to boolean in JavaScript?

vote vote



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

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


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.

vote vote



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?


or with jQuery

vote vote


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);     } } 
vote vote


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 
vote vote


Remember to match case:

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

Also, if it's a form element checkbox, you can also detect if the checkbox is checked:

var isTrueSet = document.myForm.IS_TRUE.checked; 

Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.

Top 3 video Explaining How can I convert a string to boolean in JavaScript?