There are situations in which we have a boolean value in string format (‘true’ or ‘false’) and we want its boolean equivalent (such as true or false ).

Practical application is when we have a check condition value which is stored as a string in database and based on this value we want to perform some operation on our html page (or jsp).



boolean

Off course, we can compare the string returned from database with ‘true’ and ‘false’ and get aas a result but this maybe a perfect solution.Below, I have tried to collect some approaches to achieve this.

Method 1 : Using test method

var stringValue = "true" ; var boolValue = ( /true/i ) . test ( stringValue ) //returns true var stringValue = "true"; var boolValue = (/true/i).test(stringValue) //returns true

Detail: test method of javascript matches a regular expression against a string. In this case we check whether the string contains true or not. Now, if the string value is ‘true’, then boolValue will be true, else a false. /i at the end of regular expression is for case insensitive match. Method 2 : Using comparison operator

var stringValue = "true" ; var boolValue = ( stringValue == "true" ) ; //returns true var stringValue = "true"; var boolValue = (stringValue =="true"); //returns true

Detail : We are using javascript equality operator to check the string value against a ‘true’. If the string value is ‘true’, then the boolean value will also have a true , else a false .

Method 3 : Using JSON.parse

var stringValue = "true" ; var boolValue = JSON. parse ( stringValue ) ; //returns true var stringValue = "true"; var boolValue = JSON.parse(stringValue); //returns true

Detail : Here we use the parse method of JSON . JSON is a built-in object of javascript and its parse method parses a string as JSON and converts it into an object corresponding to the given text. So, if the string value is ‘true’, it is converted to a boolean object with value as true and false otherwise. Tired of reading… Watch video!!!

Method 4 : Using ternary operator

var stringValue = "true" ; var boolValue = stringValue. toLowerCase ( ) == 'true' ? true : false ; //returns true var stringValue = "true"; var boolValue = stringValue.toLowerCase() == 'true' ? true : false; //returns true

Detail : Here, we simply check the string for its equality with ‘true’ and return a boolean true if there is a match and false otherwise using a ternary operator. Method 5 : Using switch-case

var stringValue = "true" ; var boolValue = getBoolean ( stringValue ) ; //returns true function getBoolean ( value ) { switch ( value ) { case true : case "true" : case 1 : case "1" : case "on" : case "yes" : return true ; default : return false ; } } var stringValue = "true"; var boolValue = getBoolean(stringValue); //returns true function getBoolean(value){ switch(value){ case true: case "true": case 1: case "1": case "on": case "yes": return true; default: return false; } }

