Javascript check if string if true or false and convert to Boolean

Try JSON.parse().

"true" and "false" are actually json representations of true, false. This is how ajax parses json object as a string from server side. If on server side, we return true, false => the browser will receive it as a string "true" or "false" (json representation)

if ( $(this).val() == "true" ||  $(this).val() == "false") {
    ao[id] = JSON.parse($(this).val());
}else {
    ao[id] = $(this).val();
}

DEMO


This might be slightly more elegant:

var thisval = $(this).val();

if (thisval === "true" || thisval === "false") {
    thisval = (thisval === "true");
}

Most readable:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : 
         thisval === 'false' ? false : 
         thisval;

One-liner based on the conditional operator:

var thisval = $(this).val();
ao[id] = thisval === 'true' ? true : (thisval === 'false' ? false : thisval);

One-liner based on || and && behavior:

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval !== 'false') && thisval || false;

Shortest one-liner (combination of the above):

var thisval = $(this).val();
ao[id] = thisval === 'true' || (thisval === 'false' ? false : thisval);

String.prototype.bool = function() {
    return (/^true$/i).test(this);
};


if ( $(this).val() == "true" ||  $(this).val() == "false") {
    ao[id] = $(this).val().bool();
}else {
    ao[id] = $(this).val();
}

Tags:

Javascript