How can I convert a string to boolean in JavaScript?
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Do:
using the identity operator (
===
), which doesn’t make any implicit type conversions when the compared variables have different types.This will set
isTrueSet
to a booleantrue
if the string is “true” and booleanfalse
if it is string “false” or not set at all.Don’t:
You should probably be cautious about using these two methods for your specific needs:
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.I think this is much universal:
if (String(a).toLowerCase() == "true")
…It goes:
Remember to match case:
Also, if it’s a form element checkbox, you can also detect if the checkbox is checked:
Assuming that if it is checked, it is “set” equal to true. This evaluates as true/false.