2

Is there a single function (or language construct) I can use to evaluate only the following values to true (and any other values to false)?

var trueValues = [
    true,               // boolean literal
    "true",             // string literal
    "\t tRUe ",         // case-insensitive string literal with leading/trailing whitespace
    1,                  // number literal
    1.00,               // number literal
    "1",                // string literal of number literal
    "1.0",              // string literal of number literal
    "1.00000000"        // string literal of number literal
];
core
  • 32,451
  • 45
  • 138
  • 193
  • 1
    `!!~trueValues.indexOf(something)`. (You *did* specify "only the following values".) –  Jul 10 '12 at 17:41
  • Potential Duplicate: http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript – srini.venigalla Jul 10 '12 at 17:41
  • all of the values you gave would evaluate to `true` when cast to a boolean anyways. what are you trying to accomplish? – jbabey Jul 10 '12 at 17:42
  • Sounds a bit icky. You want `\t tRUe` to be `true`, but `\t tRe` to be `false`. Perhaps you should rethink your needs. – pimvdb Jul 10 '12 at 17:47
  • Anybody knows , how to distinguish `1.00` from `1`? – Engineer Jul 10 '12 at 17:49
  • @Engineer ECMAScript doesn't provide a mechanism for telling the difference between exact value floats and integers. – Brian Nickel Jul 10 '12 at 18:16

2 Answers2

4

Assuming you mean those as examples and you really mean:

  1. Interpreted as a string, contains only the case-insensitive word "true" with optional surrounding whitespace.
  2. Interpreted as a number, evaluates to exactly 1.

The following two conditions will filter out all exceptional values.

/^\s*true\s*$/i.test(value) || Number(value) == 1
Brian Nickel
  • 26,890
  • 5
  • 80
  • 110
1

The following will trim any whitespace, change it to lowercase, and compare it to the string literal true. The other case that will return a true value is a number that returns 1 when passed to parseInt()

if(!String.prototype.trim) {
  bool = (val.replace(/^\s\s*/, '').replace(/\s\s*$/, '').toLowerCase() === "true" || Number(val) === 1)
} else {
  bool = (val.trim().toLowerCase() === "true" || Number(val) === 1)
}
Cecchi
  • 1,525
  • 9
  • 9
  • Good point, updated to look more like your solution except with a fallback to `.trim()`... debatable which is better but I'm liking yours for its simplicity and readability. – Cecchi Jul 10 '12 at 17:52