How can I convert a string to boolean in JavaScript?
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());