DEV Community

loading...
Cover image for How can I convert a string to boolean in JavaScript?

How can I convert a string to boolean in JavaScript?

courseprobe profile image Course Probe ・2 min read

In this short tutorial we are going to explore some options to convert a string to boolean in Javascript, you might have a value which is a string “true” or “false” and you need that javascript string to be a boolean value (1 or 0 / true or false).

So there might be different ways to cast to boolean, some examples of true and false conversion in javascript might use vanilla js or some libraries, let’s explore some examples below.

Example 1:

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 2:

if (String(a).toLowerCase() == "true") ...

It goes:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false
Enter fullscreen mode Exit fullscreen mode

Example 3:

var parseBool = function(str) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)

    if(str == null)
        return false;

    if (typeof str === 'boolean')
    {
        return (str === true);
    } 

    if(typeof str === 'string')
    {
        if(str == "")
            return false;

        str = str.replace(/^\s+|\s+$/g, '');
        if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
            return true;

        str = str.replace(/,/g, '.');
        str = str.replace(/^\s*\-\s*/g, '-');
    }

    // var isNum = string.match(/^[0-9]+$/) != null;
    // var isNum = /^\d+$/.test(str);
    if(!isNaN(str))
        return (parseFloat(str) != 0);

    return false;
}
Enter fullscreen mode Exit fullscreen mode

Resources which might be interesting:

Get the Book: Frontend Interview Questions

source: https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript


Other Dev posts:

Discussion (0)

pic
Editor guide