core
core

Reputation: 33059

JavaScript: Parsing a bool

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
];

Upvotes: 2

Views: 277

Answers (2)

Cecchi
Cecchi

Reputation: 1535

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)
}

Upvotes: 1

Brian Nickel
Brian Nickel

Reputation: 27550

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

Upvotes: 4

Related Questions