Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast a bool in JavaScript [duplicate]

Tags:

javascript

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 !

like image 910
Patrik Avatar asked Jan 04 '11 14:01

Patrik


4 Answers

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

like image 144
Pointy Avatar answered Nov 11 '22 03:11

Pointy


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;
}
like image 21
Jon Avatar answered Nov 11 '22 03:11

Jon


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!

like image 9
El Ronnoco Avatar answered Nov 11 '22 05:11

El Ronnoco


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.

like image 3
Šime Vidas Avatar answered Nov 11 '22 05:11

Šime Vidas