Possible Duplicate:
How can I convert a string to boolean in JavaScript?
Hi,
How can I cast a String in Bool ?
Example: "False" to bool false
I need this for my JavaScript.
Thank you for help !
You can do this:
var bool = !!someString;
If you do that, you'll discover that the string constant "False"
is in fact boolean true
. Why? Because those are the rules in Javascript. Anything that's not undefined
, null
, the empty string (""
), or numeric zero is considered true
.
If you want to impose your own rules for strings (a dubious idea, but it's your software), you could write a function with a lookup table to return values:
function isStringTrue(s) {
var boolValues = { "false": true, "False": true, "true": true, "True": true };
return boolValues[s];
}
maybe.
edit — fixed the typo - thanks @Patrick
You can use something like this to provide your own custom "is true" test for strings, while leaving the way other types compare unaffected:
function isTrue(input) {
if (typeof input == 'string') {
return input.toLowerCase() == 'true';
}
return !!input;
}
function castStrToBool(str){
if (str.toLowerCase()=='false'){
return false;
} else if (str.toLowerCase()=='true'){
return true;
} else {
return undefined;
}
}
...but I think Jon's answer is better!
function castBool(str) {
if (str.toLowerCase() === 'true') {
return true;
} else if (str.toLowerCase() === 'false') {
return false;
}
return ERROR;
}
ERROR
is whatever you want it to be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With