Reputation: 33059
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
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
Reputation: 27550
Assuming you mean those as examples and you really mean:
The following two conditions will filter out all exceptional values.
/^\s*true\s*$/i.test(value) || Number(value) == 1
Upvotes: 4