How can I convert a string to boolean in JavaScript?

Asked 2023-09-20 20:16:49 View 300,725

Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

  • "Is there a better way to accomplish this?" - there is certainly a worse way :D string=(string==String(string?true:false))?(string?true:false):(!string?true:fa‌​lse); - anyone
  • Easily handle strings and bools: function parseBool(val) { return val === true || val === "true" } - anyone
  • @Mark function checkBool(x) { if(x) {return true;} else {return false;} } - anyone
  • @Sebi: You forgot to document it: if (checkBool(x) != false) { ... } else { ... } - anyone
  • !!(parseInt(value) || value === "true") - anyone

Answers

Do:

var isTrueSet = (myValue === 'true');

using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types.

This will set isTrueSet to a boolean true if the string is "true" and boolean false if it is string "false" or not set at all.

For making it case-insensitive, try:

var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');

Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

Answered   2023-09-20 20:16:49

  • myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here. - anyone
  • I follow Crockford's advice and use === and !== whenever it makes sense, which is almost always. - anyone
  • @guinaps most of the javascript strict conventions to blanket apply to all javascript usage just cause convoluted code and a lack of understanding of the principles, theory, or usage of javascript. - anyone
  • === should be used because it's also checking for the right type. Also, it has better comparison performances than ==. - anyone
  • Thanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans. - anyone

Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".

An invalid json string passed into these functions below WILL throw an exception.


Original answer:

How about?

JSON.parse("True".toLowerCase());

or with jQuery

$.parseJSON("TRUE".toLowerCase());

Answered   2023-09-20 20:16:49

  • The problem with this is that many potential value generate a parse error which stops JS execution. So running JSON.parse("FALSE") bombs Javascript. The point of the question, I think, is not to simply solve these exact cases, but also be resilient to other cases. - anyone
  • It's pretty simple to just say JSON.parse("TRUE".toLowerCase()) so that it can parse correctly. - anyone
  • @BishopZ : Stopping JS execution is probably a desirable feature following best-pattern coding styles: en.wikipedia.org/wiki/Fail-fast - anyone
  • If we go by question title alone it goes out of discussion all that JSON thing. The question was about a string not about what can result from its transformation. Of course looking at an object "stored" in a string using the JSON format one can ask what happens in such a scenario. Or we could go as well another way towards strings converted in numbers (not into objects) for example let x = 0 + "-0" // "0-0" versus let x = 0 - "-0" // 0 but, again, we move out of main topic :) - anyone
  • Careful with JSON.parse as it is one of the source of DOM-based client-side JSON injection. portswigger.net/web-security/dom-based/… - anyone
const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}

Answered   2023-09-20 20:16:49

  • Actually it can be simplified. 1) There is no need to test for "true", "yes" and "1". 2) toLowerCase does not return null. 3) Boolean(string) is the same as string!=="" here. => switch(string.toLowerCase()) {case "false": case "no": case "0": case "": return false; default: return true;} - anyone
  • Note, this will default to true - for example: stringToBoolean('banana') // true - anyone
  • The result of JSON.parse(stringValue) will be of return type "number" instead of a "boolean" if you input a number. Otherwise fine. Your function's name is stringToBoolean, not stringToNumberOrBooleanOrError. Also, if you pass undefined, you get a JSON.parse error, which is (might be) fine, but lets the programmer at a loss as to where the error is (if there's no stacktrace...). - anyone
  • I think the question is asking about only converting the string 'true' -> true (native type) and 'false' -> false (native type). But, if you want to do a truthy/falsey conversion are you are here, you could just add !! to the front: const convertedVar = !!'myString' // is true - anyone

I think this is much more universal:

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

Answered   2023-09-20 20:16:49

  • When you can receive a string in uppercase or a boolean, then String(a).toLowerCase() === 'true' - anyone

Remember to match case:

var isTrueSet = (myValue.toLowerCase() === 'true');

Also, if it's a form element checkbox, you can also detect if the checkbox is checked:

var isTrueSet = document.myForm.IS_TRUE.checked;

Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.

Answered   2023-09-20 20:16:49

  • This will fail if myValue is null or undefined or any type other than a string. - anyone

This is the easiest way to do boolean conversion I came across recently. Thought of adding it.

JSON.parse('true');

let trueResponse = JSON.parse('true');

let falseResponse = JSON.parse('false');

console.log(trueResponse);
console.log(falseResponse);

Answered   2023-09-20 20:16:49

  • This works, but you have to be careful not to pass it empty strings or it'll pop. - anyone
  • the sexy solution, I liked it! - anyone
  • take all my money! 💵 - anyone
  • This is a quick and dirty solution for storing true/false inside .env - anyone
  • should wrap in try/catch in many cases - anyone

You can use regular expressions:

/*
 * Converts a string to a bool.
 *
 * This conversion will:
 *
 *  - match 'true', 'on', or '1' as true.
 *  - ignore all white-space padding
 *  - ignore capitalization (case).
 *
 * '  tRue  ','ON', and '1   ' will all evaluate as true.
 *
 */
function strToBool(s)
{
    // will match one and only one of the string 'true','1', or 'on' rerardless
    // of capitalization and regardless off surrounding white-space.
    //
    regex=/^\s*(true|1|on)\s*$/i

    return regex.test(s);
}

If you like extending the String class you can do:

String.prototype.bool = function() {
    return strToBool(this);
};

alert("true".bool());

For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:

Object.defineProperty(String.prototype, "com_example_bool", {
    get : function() {
        return (/^(true|1)$/i).test(this);
    }
});
alert("true".com_example_bool);

(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)

Answered   2023-09-20 20:16:49

  • You can always prefix the function if you're afraid that it'll interfere with some other code. If some code still breaks, that code is just too brittle and should be fixed. If your added function makes the object too heavy where it cause a performance issue for other code, then, obviously you don't want to do that. But, I don't think it's generally a bad idea to extend built-in objects. They also wouldn't be publicly extendable if that was the case. - anyone
  • @DTrejo @Szymon I disagree. This is exactly the kind of thing overloading the prototype is for. If you're afraid of it breaking (poor) code that relies on for..in, there are ways to hide properties from enumeration. See Object.defineProperty. - anyone
  • I love the simplicity of the regex approach to check for values that are typically "true". A suggestion for modification: the logic of false is 0 and true is non-zero. Therefore I think it's better to check for the opposite of false, i.e. return !(/^(false|0|off|no)$/i).test(this); -- also notice that I included "no". - anyone
  • Most of this answer is actually not very performant. If you can make any assumptions about your input, such as the input never being "on" or "tRUe", then it would pay to not overengineer your implementation. Extending String.prototype is never okay. - anyone

Wood-eye be careful. After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:

Let's start with the shortest, but very strict way:

var str = "true";
var mybool = JSON.parse(str);

And end with a proper, more tolerant way:

var parseBool = function(str, strict) 
{
    // console.log(typeof str);
    // strict: JSON.parse(str)
    
    if (str == null)
    {
        if (strict)
            throw new Error("Parameter 'str' is null or undefined.");

        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;
}

Testing:

var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", "  true  ", "  TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");

var array_2 = new Array(null, "", false, "false", "   false   ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");


for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}

for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}

for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}

Answered   2023-09-20 20:16:49

  • if(str == null) return false; will return random errors each time an input is wrongly initialized to null. Being tolerant is not a desirable feature most of the times: - anyone
  • @earizon: No, it will not "return random errors" - it will return false - BUT that behaviour may then cause random errors in your application. Feel free to instead throw an error if the value is null/undefined. Btw, now solved by overload strict = true. Pass strict = true, and you will now get an error on parse. - anyone
  • it depends on whether the invoked function is considered the "source of true" and invoking functions must adapt to its implementation, or whether the invoked function is an utility/service that must comply with what invoking functions are expecting according to "some contract". In general, coding conditional logic based on nulls force knowledge by calling functions of internal implementation of called one. Throwing is safer and (much) simpler. google.com/search?channel=fs&q=billion+dollar+mistake (100% agree about using strict mode) - anyone

I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:

function isTrue(value){
    if (typeof(value) === 'string'){
        value = value.trim().toLowerCase();
    }
    switch(value){
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default: 
            return false;
    }
}

It's not necessary to cover all the false cases if you already know all of the true cases you'd have to account for. You can pass anything into this method that could pass for a true value (or add others, it's pretty straightforward), and everything else would be considered false

Answered   2023-09-20 20:16:49

Universal solution with JSON parse:

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

getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false

UPDATE (without JSON):

function getBool(val){ 
    var num = +val;
    return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}

I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/

Answered   2023-09-20 20:16:49

  • The 'without JSON' version has some flaw: val="0" ; console.log(!!(+val||String(val).toLowerCase().replace(!!0,'')) ); produces true - anyone
  • getBool(undefined) will crash When using the original JSON version and will return true for the 2nd version. Here is a 3rd version which returns false: function getBool(val) { var num; return val != null && (!isNaN(num = +val) ? !!num : !!String(val).toLowerCase().replace(!!0,'')); } - anyone

Your solution is fine.

Using === would just be silly in this case, as the field's value will always be a String.

Answered   2023-09-20 20:16:49

  • Why you think it would be silly to use ===? In terms of performance it would be exactly the same if both types are Strings. Anyway, I rather use === since I always avoid the use of == and !=. Justifications: stackoverflow.com/questions/359494/… - anyone
  • Since value will always be a string neither == nor === are silly. Both are the right tool for this job. They only differ when the types are not equal. In that case === simply returns false while == executes an intricate type coercion algorithm before comparison. - anyone
  • In most code styles, using == is bad practice. When you read the code and see ==, it makes you stop and wonder is it a bug or some special trick. Therefore, it is better when your code is consistent. And == leaves room for a potential error in the future. Because types can change. - anyone

The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.

If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false.

Keep in mind the performance and security implications when using eval() though.

Answered   2023-09-20 20:16:49

  • To understand what's "wrong" (or right) with eval - check out articles like javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval or search on stackoverflow for 'Javascript eval malware' - anyone
  • I agree that var isTrueSet = (myValue === 'true'); is the best answer. - anyone
  • I like that it's concise. But it fails spectacularly for the basic case of eval('TRUE'); proving once again, that eval() is evil. - anyone
  • @10basetom: Quite correct. You should include .toLowerCase() in the answer is my point. I'm not trying to force anything. Uppercase TRUE is a common enough value to be returned by many UI widgets. - anyone
  • Quoting mozzila docs: Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…! - anyone
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) { 
    return !falsy.test(val) && !!val;
};

This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).

// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();

//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());

Answered   2023-09-20 20:16:49

  • I feel bad for those who don't scroll and just pick the top answer. This answer is robust, reusable, and succinct. I shortened it into a one-liner: Boolean.parse ??= (val) => {return !/^(?:f(?:alse)?|no?|0+)$/i.test(val) && !!val}; - anyone

There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.

Brief of results (the higher the better):

  1. Conditional statement: 2,826,922
  2. Switch case on Bool object: 2,825,469
  3. Casting to JSON: 1,867,774
  4. !! conversions: 805,322
  5. Prototype of String: 713,637

They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.

Answered   2023-09-20 20:16:49

  • "something went wrong" when trying to view jsPerf test - anyone

This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive

var isTrueSet = (myValue.toLowerCase() === 'true');

Answered   2023-09-20 20:16:49

  • not to mention that .toLowerCase might throw if myValue is equal to null or undefined - anyone

I use the following:

function parseBool(b) {
    return !(/^(false|0)$/i).test(b) && !!b;
}

This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".

Answered   2023-09-20 20:16:49

Simplest solution 🙌🏽

with ES6+

use the logical NOT twice [ !! ] to get the string converted

Just paste this expression...

const stringToBoolean = (string) => string === 'false' ? false : !!string

And pass your string to it!

stringToBoolean('')                 // false
stringToBoolean('false')            // false
stringToBoolean('true')             // true
stringToBoolean('hello my friend!') // true
🤙🏽 Bonus! 🤙🏽
const betterStringToBoolean = (string) => 
  string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?
  false : !!string

You can include other strings at will to easily extend the usage of this expression...:

betterStringToBoolean('undefined')     // false
betterStringToBoolean('null')          // false
betterStringToBoolean('0')             // false
betterStringToBoolean('false')         // false
betterStringToBoolean('')              // false
betterStringToBoolean('true')          // true
betterStringToBoolean('anything else') // true

Answered   2023-09-20 20:16:49

  • How about '1'? Should it be converted to true or false? I think it is should be true, no? But using your answer, it will returns false - anyone
  • Guess you are doing something wrong bro... I just tested the code and if you input ' 1 ' the return is always true. Don't know how you got that false but I think you must be messing it up in some way - anyone
  • Ah sorry! My bad, I was testing the first function instead. Thanks for clarifying this. - anyone
  • Your examples are all strings. For example 'null' is not actual null, it's a string with characters null in it. - anyone

The expression you're looking for simply is

/^true$/i.test(myValue)

as in

var isTrueSet = /^true$/i.test(myValue);

This tests myValue against a regular expression , case-insensitive, and doesn't modify the prototype.

Examples:

/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz");  // returns false

Answered   2023-09-20 20:16:50

you can use JSON.parse as follows:

   
var trueOrFalse='True';
result =JSON.parse(trueOrFalse.toLowerCase());
if(result==true)
  alert('this is true');
else 
  alert('this is false');

in this case .toLowerCase is important

Answered   2023-09-20 20:16:50

  • Not guaranteed to return a boolean, though. - anyone
Boolean.parse = function (str) {
  switch (str.toLowerCase ()) {
    case "true":
      return true;
    case "false":
      return false;
    default:
      throw new Error ("Boolean.parse: Cannot convert string to boolean.");
  }
};

Answered   2023-09-20 20:16:50

  • You can use true.toString() instead of "true" to be even more clean :-) - anyone
  • Don't change globals, try to keep your changes isolated, maybe create a new function parseBoolean instead - anyone

There are already so many answers available. But following can be useful in some scenarios.

// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];

function getBoolean(a) {
    return TRUTHY_VALUES.some(function(t) {
        return t === a;
    });
}

This can be useful where one examples with non-boolean values.

getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false

getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true

Answered   2023-09-20 20:16:50

I'm suprised that includes was not suggested

let bool = "false"
bool = !["false", "0", 0].includes(bool)

You can modify the check for truely or include more conditions (e.g. null, '').

Answered   2023-09-20 20:16:50

  • hmm, this is perfect - anyone
  • I'm using this approach for a framework that parses URL parameters and includes parameters without values as an empty string, something like: example.com?useSpecialFeature ends up as {useSpecialFeature:''} - anyone

To convert both string("true", "false") and boolean to boolean

('' + flag) === "true"

Where flag can be

 var flag = true
 var flag = "true"
 var flag = false
 var flag = "false"

Answered   2023-09-20 20:16:50

This function can handle string as well as Boolean true/false.

function stringToBoolean(val){
    var a = {
        'true':true,
        'false':false
    };
    return a[val];
}

Demonstration below:

function stringToBoolean(val) {
  var a = {
    'true': true,
    'false': false
  };
  return a[val];
}

console.log(stringToBoolean("true"));

console.log(typeof(stringToBoolean("true")));

console.log(stringToBoolean("false"));

console.log(typeof(stringToBoolean("false")));

console.log(stringToBoolean(true));

console.log(typeof(stringToBoolean(true)));

console.log(stringToBoolean(false));

console.log(typeof(stringToBoolean(false)));

console.log("=============================================");
// what if value was undefined? 
console.log("undefined result:  " + stringToBoolean(undefined));
console.log("type of undefined result:  " + typeof(stringToBoolean(undefined)));
console.log("=============================================");
// what if value was an unrelated string?
console.log("unrelated string result:  " + stringToBoolean("hello world"));
console.log("type of unrelated string result:  " + typeof(stringToBoolean(undefined)));

Answered   2023-09-20 20:16:50

One Liner

We just need to account for the "false" string since any other string (including "true") is already true.

function b(v){ return v==="false" ? false : !!v; }

Test

b(true)    //true
b('true')  //true
b(false)   //false
b('false') //false

A more exaustive version

function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }

Test

bool(true)        //true
bool("true")      //true
bool(1)           //true
bool("1")         //true
bool("hello")     //true

bool(false)       //false
bool("false")     //false
bool(0)           //false
bool("0")         //false
bool(null)        //false
bool("null")      //false
bool(NaN)         //false
bool("NaN")       //false
bool(undefined)   //false
bool("undefined") //false
bool("")          //false

bool([])          //true
bool({})          //true
bool(alert)       //true
bool(window)      //true

Answered   2023-09-20 20:16:50

  • Any specific reason for using !!v instead of using true directly? - anyone

I'm using this one

String.prototype.maybeBool = function(){

    if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
    if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;

    return this;

}

"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"

Answered   2023-09-20 20:16:50

  • This is good, but works only with String type. Imagine that this need be used by a variable that is maybe "true" or true. If come the second one, this will not work. Is possible make a document.prototypeto use this wherever we want it? - anyone
  • This looks elegant. Great job! However, I noticed that overloading basic prototypes in large JS apps (that also need unit testing) might result in some unexpected behaviour (namely, when you want to iterate with "for" through an array that has the prototype overloaded, you'll get some properties that you wouldn't normally expect). You have been warned. ;) - anyone
  • a variant of yours that accepts boolean too function StringOrElse2Bool(sob){ if (typeof sob === "string") { return ["no", "false", "0", "off"].indexOf( sob.toLowerCase() ) !== -1 ? false : true; } else { return !!sob } - anyone

why don't you try something like this

Boolean(JSON.parse((yourString.toString()).toLowerCase()));

It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as

// 0-> false
// any other number -> true

Answered   2023-09-20 20:16:50

You need to separate (in your thinking) the value of your selections and the representation of that value.

Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)

In other words, yes, you need to depend on the string's value. :-)

Answered   2023-09-20 20:16:50

another solution. jsFiddle

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

test cases run in node

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

Answered   2023-09-20 20:16:50

Hands down the easiest way (assuming you string will be 'true' or 'false') is:

var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false

Always use the === operator instead of the == operator for these types of conversions!

Answered   2023-09-20 20:16:50

  • What conversion were you talking about? :-) - anyone
  • When comparing string in javascript there is no difference between using the == or === operators when not using conversions. Here you are comparing to strings, therefore no type conversions. See stackoverflow.com/questions/359494/… - anyone