This article will explain how to convert “String” to “Boolean” in JavaScript. So let’s start.
Ways To Convert String To Boolean
There is a total of 5 ways, using them we can convert string value to boolean value.
- Using test() Method
- Using JSON.parse()
- Using Comparison Operator
- Using The Ternary Operator
- Using Switch Case
Below are the examples.
1. Using test() Method
JavaScript test() method will match the regular expression on a string. Using test(), we can simply check whether the string contains “true” or not. If yes then it will give us the boolean value “true” or else “false“. Check the below code for example and try with your console.
var string = "true"; var boolean = (/true/i).test(string); //true console.log(boolean);
2. Using JSON.parse()
This is the most used method in web applications based on JS. This method parses the string as JSON and converts it to an object. So if the string value is ‘true’ then it will be converted to a boolean object with the value true else false.
var string = "true"; var boolean = JSON.parse(string); //true console.log(boolean);
3. Using Comparision Operator
Using the double equal sign(==), We can compare the value of operands on it on both sides (right, and left). It will return true if both the values are the same else false.
var string = "true"; var boolean = (string == 'true') //true console.log(boolean);
4. Using Ternary Operator
It is so easy to use. In this case, we simply check the equality of the value with ‘true’ and return the boolean value true if the condition is satisfied or else false.
var string = "true"; var boolean = string.toLowerCase() == "true" ? true : false //true console.log(boolean);
5. Using Switch Case
Check the below code to convert a string to a boolean value using the switch case.
var string = "true"; var boolean = getBooleanVal(string); //returns true function getBooleanVal(value){ switch(value) { case true: case "true": case 1: case "1": case "on": case "yes": return true; default: return false; } } console.log(boolean);