JavaScript: Parsing a string Boolean value? [duplicate]

I would be inclined to do a one liner with a ternary if.

var bool_value = value == "true" ? true : false

Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

var bool_value = value == 'true';

This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.


You can use JSON.parse for that:

JSON.parse("true"); //returns boolean true

It depends how you wish the function to work.

If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:

function parseBoolean(str) {
  return /true/i.test(str);
}

If you wish to assure that the entire string is the word true you could do this:

function parseBoolean(str) {
  return /^true$/i.test(str);
}

You can try the following:

function parseBool(val)
{
    if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
        return true;
    else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
        return false;

    return null;
}

If it's a valid value, it returns the equivalent bool value otherwise it returns null.


You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:

function test (input) {
    try {
        return !!$.parseJSON(input.toLowerCase());
    } catch (e) { }
}