200

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

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

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
user160820
  • 14,296
  • 21
  • 61
  • 92

3 Answers3

390
var val = (string === "true");
Deduplicator
  • 43,322
  • 6
  • 62
  • 109
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
  • 10
    This works. It's probably better to add `var` before the declaration of `val`. – hotshot309 Jan 03 '12 at 20:58
  • 7
    Even better with a triple equals === – Vinch Apr 11 '13 at 22:02
  • 1
    If you do somehting like: var string = new String('true'); var val = (string === 'true'); Then val will be false. you need to call .toString() on the string reference. This is especially applicable if you are doing this on a prototype / this reference to the string. – Boushley Nov 26 '13 at 20:53
  • 18
    Another improvement is to change "string" to "string.toLowerCase()". This allows for "string" to have other encodings of true like "True" and "TRUE". – Max Strater Mar 11 '14 at 00:45
  • 7
    var val = string.match(/true/i); // case insensitive match – stephenbayer Apr 11 '14 at 16:05
  • 7
    var val = string.match(/^(true|yes|t|y|1)$/i); /* case insensitive + many + whole word */ – Andrew Philips Aug 28 '14 at 16:46
  • 3
    Instead of playing with regex, how about: `var val = (string.toLowerCase() === 'true');` – JKirchartz Jun 29 '15 at 20:49
  • @MaxStrater that's an excellent idea. In my case, VB Razor is creating my string, which (because of VB's silliness) enters it as "True" or "False" (aka sentence case) – Jacob Stamm Feb 18 '16 at 23:04
  • One can also use JSON.parse(var), if value is fetched from database and is of string type. – Akash Saxena Jan 06 '17 at 10:47
  • myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here – paparoch Mar 23 '18 at 18:12
  • Very good @ Boushley! Happens exactly the same if you use TypeScript instead of JS. Many, many THANKs! You just can't state `val = (objProp === "true")` if "by accident" `objProp ` is a (fake!) boolean. – Pedro Ferreira Mar 08 '19 at 17:34
27

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

andrewmu
  • 13,818
  • 4
  • 37
  • 37
15

If you're using the variable result:

result = result == "true";
clarkf
  • 3,012
  • 19
  • 14
  • 2
    If you're using the variable result: `result = result === "true";` Here the parentheses are unnecessary, but should check the type and value. – simhumileco Jun 29 '17 at 06:22