214

I have a JavaScript string containing "true" or "false".

How may I convert it to boolean without using the eval function?

3
  • 24
    JSON.parse('true') will return boolean true and JSON.parse('false') will return boolean false Commented Jan 2, 2017 at 7:10
  • this stuff solved everything like number and string format stackoverflow.com/a/42136805/5531595 Commented Feb 9, 2017 at 12:34
  • @HariDas Worked perfectly! I'm surprised the Boolean object wrapper doesn't properly convert "true" and "false" strings. I think it should be allowed an optional second parameter that tells it to attempt converting the string value to a boolean Commented Sep 6, 2022 at 20:31

3 Answers 3

411
var val = (string === "true");

Case insensitive:

const val = (string.toLowerCase() === "true");
Sign up to request clarification or add additional context in comments.

11 Comments

This works. It's probably better to add var before the declaration of val.
Even better with a triple equals ===
Another improvement is to change "string" to "string.toLowerCase()". This allows for "string" to have other encodings of true like "True" and "TRUE".
var val = string.match(/true/i); // case insensitive match
var val = string.match(/^(true|yes|t|y|1)$/i); /* case insensitive + many + whole word */
|
27

You could simply have: var result = (str == "true").

1 Comment

result = result === "true"; Here the parentheses are unnecessary, but should check the type and value.
15

If you're using the variable result:

result = result == "true";

1 Comment

If you're using the variable result: result = result === "true"; Here the parentheses are unnecessary, but should check the type and value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.