In this shot, we will cover how to convert a string into its boolean representation.
The easiest way to convert string to boolean is to compare the string with 'true'
:
let myBool = (myString === 'true');
For a more case insensitive approach, try:
let myBool = (myString.toLowerCase() === 'true');
However, toLowerCase()
will throw an error if myString
is null
or undefined
.
Remember, all other strings that are not
'true'
will be converted tofalse
, e.g.,('Test'.toLowerCase() === 'true')
evaluates tofalse
.
we can also use
!!
for a string to boolean conversion.
let myString = 'true'; let myBool = (myString.toLowerCase() === 'true'); // true console.log(myBool); myString = 'False'; myBool = (myString.toLowerCase() === 'true'); // false console.log(myBool); myString = 'Test'; myBool = (myString.toLowerCase() === 'true'); // false console.log(myBool);
RELATED TAGS
CONTRIBUTOR
View all Courses