JavaScript: Parsing a string Boolean value? [duplicate] JavaScript: Parsing a string Boolean value? [duplicate] javascript javascript

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);}