I know, I know, sounds silly, but I am having this one variable passed around and around and I think somewhere in the midst of it all its losing itself as a Boolean Value, that being the case I need to take said string when it comes to one portion of my script and make sure its read as a Boolean. So with that, I am wondering if theres something like the parseInt function but for booleans cause I know when my int's manage to get run through the mill and turn into a string cause of, I sometimes need to invoke a means of making it recognize as integer again.
3 Answers
String.prototype.parseBoolean = function ()
{
return ("true" == this.toLowerCase()) ? true : false
}
1 Comment
mkoryak
adding to native objects prototype is generally frowned upon these days stackoverflow.com/questions/6877005/… - also can be simplified by getting rid of the ternary statement and just returning the comparison.
no there is no function, there is this shortcut:
var bool = !!something;
or, you can make a new boolean like this:
var bool = Boolean(something)
it works by coercing the value to a boolean. It will use the truthy/falsy value for the variable.
while i am on this topic, there is also:
var floor = ~~3.1415; //floor = 3
1 Comment
tru7
Warning if anyone stumbles on this: !!"false" === true. And Boolean("false") === true.
function stringToBoolean(string){
if (typeof string === "undefined") {
console.log("stringToBoolean Undefined Error");
return false;
}
if (typeof string === "boolean") return string;
switch(string.toLowerCase()) {
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return false;
}
}