[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
Unnecessary:
We also used strictly equality operator(===) only when the implicit type conversions doesn't need else use normal equality operator (==).
Don't:
Boolean operator used for specific needs so we should probably be cautious about using these two methods.
- 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:
or with jQuery
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.
Solution 4:
Use regular expression (/^true$/i) to convert string into boolean
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
(It Won't work in older version of Firefox)
Solution 5:
Better way to redefine the solution 1 with the case:
we can also detect using checkbox.
Assuming that if the checkbox is checked, return true else return false.
Solution 6:
The universal way of solve this problem is:
If the string in the uppercase then use: