How to convert string to boolean | JavaScript

In JavaScript, you can convert a string to a boolean using a few different approaches. Here are the details along with examples:

Using Boolean Constructor

You can use the Boolean constructor to explicitly convert a string to a boolean value. It converts an empty string to false and any non-empty string to true.

let str = "true"; let boolValue = Boolean(str); // Converts "true" to true console.log(boolValue); // Output: true

Keep in mind that all non-empty strings are converted to true, including strings like "false".

Using Comparison

You can perform a comparison to achieve implicit string-to-boolean conversion. Any non-empty string, including "false", will be evaluated as true, while an empty string will be evaluated as false.

let str = "false"; let boolValue = str === "true"; // Converts "false" to false console.log(boolValue); // Output: false

Using JSON.parse()

This method can be used if the input string follows JSON syntax. JSON.parse() will correctly convert the string to its boolean representation.

let str = "true"; let boolValue = JSON.parse(str); // Converts "true" to true console.log(boolValue); // Output: true

Remember that these conversions are sensitive to the exact content of the string. For best results, use consistent and expected values.


How can I convert a string to boolean in JavaScript

Using Regular Expression

The test() method of JavaScript matches a regular expression against a string.

let myString = "true"; let myBool = (/true/i).test(myString) console.log(myBool); //returns true

The "/i" at the end of regular expression is for case insensitive match.

Note: If the string contains something other than "true" or "false", these methods might not give you the desired boolean result and might instead produce false.

Conclusion

You can convert a string to a boolean using methods like the Boolean constructor or comparisons for implicit conversion. The Boolean constructor converts non-empty strings to true and empty strings to false, while comparisons evaluate non-empty strings as true and empty strings as false. Additionally, JSON.parse() can be used for accurate conversion if the string follows JSON syntax.