Reputation: 32247
For numbers you can do +"10"
instead of Number("10")
which is a chunk faster. Is there a way to do this for boolean from a string?.
Upvotes: 2
Views: 451
Reputation: 41767
If matching all case variants of the word true
is the requirement, I believe using a regex is the quickest, eg:
/^true$/i.match(input)
Upvotes: 1
Reputation: 359966
It's silly to use a regexp. If you really only want to match the string 'true'
and don't care about case sensitivity, just compare against that string:
function parseBoolean(s)
{
return s === 'true';
}
I suppose if I were really going to play "fill in the blank" with you, I'd answer:
+"10" is to Number("10") as !!"true" is to Boolean("true")
since Boolean(x)
only returns false
when x
is a falsy value, that is, when x ∊ {null, undefined, false, 0, ''}
.
Upvotes: 5
Reputation: 14616
Some not-so-good and evil solutions:
window.toBool = {'false':false,'true':true};
toBool['false'] === false
eval('false') === false // don't ever do this!
JSON.parse('false')
Upvotes: 1