Skip to content

Convert String to Boolean in JavaScript

Learn different ways to converting string to boolean in JavaScript.

Using Regular Expressions

function strToBool(s)
{
    regex=/^\s*(true|1|on)\s*$/i
    return regex.test(s);
}

Using JSON Parse

function str2bool(val) {
    return !!JSON.parse(String(val).toLowerCase());
}

Using switch case

function str2bool(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(string);
    }
See also  Path Sum III - Leetcode Challenge - Java Solution
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.