[Solved-6 Solutions] Convert string to Boolean in javascript - javascript tutorial
Problem:
How to convert a string to boolean in JavaScript ?
Solution 1:
We use brackets for the value and equal it with isTrueSet
var isTrueSet = (Value == 'true');
Unnecessary:
We also used strictly equality operator(===) only when the implicit type conversions doesn't need else use normal equality operator (==).
var isTrueSet = (Value === 'true');
Don't:
Boolean operator used for specific needs so we should probably be cautious about using these two methods.
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
- It will evaluate to true except the empty string.
- Otherwise they're the cleanest methods we can think of concerning to boolean conversion.
- If they are not can we do.
Solution 2:
The solution is technically correct for a normal string. If we passed an invalid json string into the functions then it will throw an exception. In this case we use the below code:
JSON.parse("true");
or with jQuery
$.parseJSON("true");
Solution 3:
- Another way is to normalize data by using .toLowerCase().
- Then we want to throw in trim() to strip whitespace.
- And it is easy to convert string into boolean.
stringToBoolean: function(str){
switch(str.toLowerCase().trim()){
case "true": case "yes": case "1": return true;
case "false": case "no": case "0": case null: return false;
default: return Boolean(str);
}
}
Solution 4:
Use regular expression (/^true$/i) to convert string into boolean
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
In the above solution we extends the String object then we worried about clashing with other code.That why we use Object.defineProperty to release this clashes
Object.defineProperty(String.prototype, "example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".example_bool);
(It Won't work in older version of Firefox)
Solution 5:
Better way to redefine the solution 1 with the case:
var isTrueSet = (myValue.toLowerCase() === 'true');
we can also detect using checkbox.
var isTrueSet = document.myForm.IS_TRUE.checked;
Assuming that if the checkbox is checked, return true else return false.
Solution 6:
The universal way of solve this problem is:
if (String(str) == "true")
If the string in the uppercase then use:
String(str).toLowerCase() === "true"