How can I convert a string to boolean in JavaScript?
Asked Answered
C

107

3522

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

I have a hidden form in HTML that is updated based on 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?

Cryobiology answered 5/11, 2008 at 0:13 Comment(18)
Just to highlight an odd example of avoiding triple-equals comparison: I have a function currentSortDirection() that returns 1 for an ascending sort, 0 for a descending sort, and -1 for not set. Using while (currentSortDirection() != desiredSortDirection) { sortColumn() } works great, since -1 != true and -1 != false...but changing this to while (Boolean(currentSortDirection) !== ...) {...} forces -1 into a true, necessitating an additional couple of lines of prep, just to make jshint happy.Ecchymosis
Possible duplicate of stackoverflow.com/questions/263965Geognosy
@Droogans: What happens if desiredSortDirection is set to asc? I know in a controlled environment you are probably in control over the value desiredSortDirection is set to but in a shared environment when the input of desiredSortDirection can come from anywhere in any form, type-checking against custom objects and defensive programming can save a lot of hours of debugging. Your code is absolutely fine and nothing is wrong with it, I'm merely pointing out that there is no one-fit-all answer/solution and it will always be scenario dependant.Johannisberger
"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);Machicolate
Easily handle strings and bools: function parseBool(val) { return val === true || val === "true" }Cropeared
@Mark function checkBool(x) { if(x) {return true;} else {return false;} }Goodloe
@Sebi: You forgot to document it: if (checkBool(x) != false) { ... } else { ... }Machicolate
!!(parseInt(value) || value === "true")Conch
You can't, it is impossible!Gauzy
Just a note. I am always amazed by Javascript expression parsing rule-set, for example, 123+44+'2'+1 gives "16721". Every + after '2' is interpreted as concatenation operation, wow :-D. While PHP gives 170 as an answer, which is more transparent, because in PHP plus is not ambiguous - it is just used for arithmetic operations. Concatenation operation is performed with different operatorDebunk
I haven't found an answer which solves undefined+string combination properly. So eventually I wrote one-liner for this: const StrToBool = (value) => !!value && value !== "false" && parseInt(value) !== 0; This one liner gives following results: StrToBool(undefined) => false, StrToBool('true') => true, StrToBool('false') => false, StrToBool('0') => false, StrToBool('Whatever') => true, StrToBool('1') => trueSallust
!myVar.slice(4,5); myVar = 'TRUE' // true myVar = 'FALSE' // falseCabe
@AndrewLuca 's answer is great - it handles undefined, null and all other types. It considers non-zero numbers as true as well as the string 'true'. And all in a concise way.Mukund
toBool ={'false':false,'true':true } invertBool = {'false':true,'true':false} can be used toBool[string]Rapport
JSON.parse('true') is the most easiest way to convert to booleanChirlin
'true' === true is falsePoliclinic
I recently had a similar issue. I used a data attribute on an element with a true or false string. At a certain interaction I wanted to toggle the string. I came up with this: boolString = (!(/true/).test(boolString)).toString() It makes a direct string check if the string is "true". If not, it assumes "false" no matter what. Then it negates it, and makes it into a string.Ethnology
exactly is my problem my man, you're a gem to ask thisAccalia
C
4975

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.

Chilopod answered 5/11, 2008 at 0:13 Comment(9)
myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here.Luthern
I follow Crockford's advice and use === and !== whenever it makes sense, which is almost always.Chilopod
@Chilopod 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.Raddatz
=== should be used because it's also checking for the right type. Also, it has better comparison performances than ==.Kaczmarek
This doesn't account for 'false'...if the string isn't 'true' or 'false', then myBool should probably be undefined. eg let myBool = (myValue === 'true')?true:(myValue === 'false')?false:undefined;Koloski
I would instead use true as 1 and false as 0. It would allow you to use methods like parseInt() and compare it's value using if(parseInt(booleanVariable))Trigg
Thanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans.Cense
This does account for false as if the string doesn't match or is undefined then the conditional will evaluate to boolean false. I updated the answer.Paisley
Thank you so much. Better put it in a utility export function BoolFromString(value: 'true' | 'false' | string) { return (String(value).toLowerCase() === 'true'); } Fiftyfifty
P
861

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());
Pow answered 5/11, 2008 at 0:13 Comment(6)
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.Rambunctious
It's pretty simple to just say JSON.parse("TRUE".toLowerCase()) so that it can parse correctly.Sherrillsherrington
@Rambunctious : Stopping JS execution is probably a desirable feature following best-pattern coding styles: en.wikipedia.org/wiki/Fail-fastMashie
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 :)Counterweigh
Careful with JSON.parse as it is one of the source of DOM-based client-side JSON injection. portswigger.net/web-security/dom-based/…Gerson
@RaviMCA Couldn't you have come up with something a little more fact-based than that link? You may be right (though just yesterday I was reading about the difference between eval and JSON.parse, and how you use the latter to avoid the injection problems of the former) but that page is nothing more than poorly described hearsay.Abscise
E
298
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);
    }
}
Evzone answered 5/11, 2008 at 0:13 Comment(4)
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;}Redblooded
Note, this will default to true - for example: stringToBoolean('banana') // trueAndradite
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...).Cormick
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 trueProvincial
R
271

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
Rotary answered 5/11, 2008 at 0:13 Comment(1)
When you can receive a string in uppercase or a boolean, then String(a).toLowerCase() === 'true'Renounce
F
171

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.

Formicary answered 5/11, 2008 at 0:13 Comment(1)
This will fail if myValue is null or undefined or any type other than a string.Fibre
C
161

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);
Chirlin answered 5/11, 2008 at 0:13 Comment(6)
This works, but you have to be careful not to pass it empty strings or it'll pop.Filbert
the sexy solution, I liked it!Pyramidal
take all my money! 💵Aprilette
This is a quick and dirty solution for storing true/false inside .envShrimp
should wrap in try/catch in many casesConsumptive
The best. I'm using it in an input type of radio, so the value is never an empty stringHeidyheifer
G
138

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' regardless
    // of capitalization and regardless of 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)

Glendoraglendower answered 5/11, 2008 at 0:13 Comment(4)
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.Miffy
@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.Vittorio
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".Racine
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.Donata
C
85

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]));}
Cormick answered 5/11, 2008 at 0:13 Comment(3)
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:Mashie
@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.Cormick
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)Mashie
K
56

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

Kagera answered 5/11, 2008 at 0:13 Comment(0)
V
47

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/

Volumed answered 5/11, 2008 at 0:13 Comment(2)
The 'without JSON' version has some flaw: val="0" ; console.log(!!(+val||String(val).toLowerCase().replace(!!0,'')) ); produces trueHoral
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,'')); }Cherish
P
36

Your solution is fine.

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

Phiona answered 5/11, 2008 at 0:13 Comment(4)
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: #359994Maestoso
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.Redblooded
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.Trabue
I'm not entierly sure I'd claim == makes you think there's a bug or trick... all of us C/++ coders are still wondering why there are 2 equality operators when u could just cast it (hooray weakly typed languages! down w typescript!!). =)Housebreaker
R
34

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.

Resume answered 5/11, 2008 at 0:13 Comment(6)
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'Unessential
I agree that var isTrueSet = (myValue === 'true'); is the best answer.Resume
I like that it's concise. But it fails spectacularly for the basic case of eval('TRUE'); proving once again, that eval() is evil.Smriti
@Area 51 Detective Fiction, in the same fashion, JSON.parse('TRUE') from the answer below also fails spectacularly. It's quite easy to force an error condition in JavaScript (or any language, for that matter). To account for this, you should normalize the string first, e.g., var myValue = document.myForm.IS_TRUE.value.toLowerCase(); var isTrueSet = (myValue==='true' || myValue==='false') ? eval(myValue) : false;Resume
@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.Smriti
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/…!Romans
L
33
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());
Lacielacing answered 5/11, 2008 at 0:13 Comment(1)
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};Petrina
E
24

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.

Empiricism answered 5/11, 2008 at 0:13 Comment(1)
"something went wrong" when trying to view jsPerf testHyaluronidase
E
21

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');
Enlistee answered 5/11, 2008 at 0:13 Comment(1)
not to mention that .toLowerCase might throw if myValue is equal to null or undefinedAdiel
C
19

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
Chante answered 5/11, 2008 at 0:13 Comment(4)
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 falseYen
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 wayChante
Ah sorry! My bad, I was testing the first function instead. Thanks for clarifying this.Yen
Your examples are all strings. For example 'null' is not actual null, it's a string with characters null in it.Protohuman
B
19

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".

Bertine answered 5/11, 2008 at 0:13 Comment(0)
E
18

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
Eniwetok answered 5/11, 2008 at 0:13 Comment(1)
This is very neat.Protohuman
N
17

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

Nims answered 5/11, 2008 at 0:13 Comment(1)
Not guaranteed to return a boolean, though.Gomulka
L
14

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, '').

Laoag answered 5/11, 2008 at 0:13 Comment(2)
hmm, this is perfectNadeen
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:''}Selfabsorbed
F
14

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
Fourteen answered 5/11, 2008 at 0:13 Comment(0)
P
14
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.");
  }
};
Prehensile answered 5/11, 2008 at 0:13 Comment(2)
You can use true.toString() instead of "true" to be even more clean :-)Prinz
Don't change globals, try to keep your changes isolated, maybe create a new function parseBoolean insteadCulbert
R
13

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"
Rudman answered 5/11, 2008 at 0:13 Comment(0)
R
12

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)));
Ramekin answered 5/11, 2008 at 0:13 Comment(0)
C
11

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
Crude answered 5/11, 2008 at 0:13 Comment(1)
Any specific reason for using !!v instead of using true directly?Unscientific
S
10

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
Storer answered 5/11, 2008 at 0:13 Comment(0)
F
10

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"
Forrer answered 5/11, 2008 at 0:13 Comment(3)
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?Richly
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. ;)Blowfly
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 }Araarab
B
9

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
> 
Boyce answered 5/11, 2008 at 0:13 Comment(0)
C
9

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. :-)

Cardiomegaly answered 5/11, 2008 at 0:13 Comment(0)
M
8

Holy god some of these answers are just wild. I love JS and its infinite number of ways to skin a bool.

My preference, which I was shocked not to see already, is:

testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;
Martines answered 5/11, 2008 at 0:13 Comment(0)
E
8

I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/filthy-ness but includes "false" as an acceptible value for false.

I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.

var value = "false";
var result = (value == "false") != Boolean(value);

// value = "true"  => result = true
// value = "false" => result = false
// value = true    => result = true
// value = false   => result = false
// value = null    => result = false
// value = []      => result = true
// etc..
Eirena answered 5/11, 2008 at 0:13 Comment(0)
Z
8

Like @Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides "true" and "false" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:

function parseBoolean(string) {
  switch (String(string).toLowerCase()) {
    case "true":
    case "1":
    case "yes":
    case "y":
      return true;
    case "false":
    case "0":
    case "no":
    case "n":
      return false;
    default:
      //you could throw an error, but 'undefined' seems a more logical reply
      return undefined;
  }
}
Zymogenic answered 5/11, 2008 at 0:13 Comment(0)
B
8

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!

Bomber answered 5/11, 2008 at 0:13 Comment(2)
What conversion were you talking about? :-)Lutyens
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 #359994Flunkey
B
7

The simplest way which I always use:

let value = 'true';
let output = value === 'true';
Bilabial answered 5/11, 2008 at 0:13 Comment(4)
Ternary operator is not necesary. Only with let output = value === 'true' works.Mowry
let value = 'true'; let output = value === 'true' ? true : false; output = true; let value = 'false'; let output = value === 'true' ? true : false; output = false; What is not working here?Bilabial
Sorry, it has been a missunderstanding. That works perfectly, but it's redundant. value === 'true' already returns a boolean value and ternary operator is not necesary.Mowry
Yeah sure you are right, I edited my answered - my fault ;]Bilabial
R
7

My take on this question is that it aims to satisfy three objectives:

  • Return true/false for truthy and falsey values, but also return true/false for multiple string values that would be truthy or falsey if they were Booleans instead of strings.
  • Second, provide a resilient interface so that values other than those specified will not fail, but rather return a default value
  • Third, do all this with as little code as possible.

The problem with using JSON is that it fails by causing a Javascript error. This solution is not resilient (though it satisfies 1 and 3):

JSON.parse("FALSE") // fails

This solution is not concise enough:

if(value === "TRUE" || value === "yes" || ...) { return true; }

I am working on solving this exact problem for Typecast.js. And the best solution to all three objectives is this one:

return /^true$/i.test(v);

It works for many cases, does not fail when values like {} are passed in, and is very concise. Also it returns false as the default value rather than undefined or throwing an Error, which is more useful in loosely-typed Javascript development. Bravo to the other answers that suggested it!

Rambunctious answered 5/11, 2008 at 0:13 Comment(2)
Just to go back to your objectives, the only problem with your third & best solution is that it does not meet Objective #1 - it will only return true for a value of 'true', but not for any truthy input. In order to make it meet Objective #1, it is only slightly more concise than Solution #2, and far less readable.Changsha
return /^(true|yes|1|t|y)$/i.test(str);Titfer
U
6

Dead-simple, best performing and strict

Best performance according to https://mcmap.net/q/40379/-how-can-i-convert-a-string-to-boolean-in-javascript

Type safe and strict answer (great if you want to enforce stricter rules on your inputs) that I did not see in all other answers, also gives you a clear explanation in the console when it gets an incorrect input:

Typescript version:

function parseBool(value: any):boolean {
  if (value === 'true') return true
  if (value === 'false') return false
  console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
  throw new Error('Error: parseBool got unexpected value')
}

Arrow function version:

const parseBool = (value: any):boolean => {
  if (value === 'true') return true
  if (value === 'false') return false
  console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
  throw new Error('Error: parseBool got unexpected value')
}

Javascript version:

function parseBool(value){
  if (value === 'true') return true
  if (value === 'false') return false
  console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
  throw new Error('Error: parseBool got unexpected value')
}
Unhallow answered 5/11, 2008 at 0:13 Comment(3)
You should consider normal Boolean values also in the function in case they are passed to the function.Stickney
You may also want to consider using .toLowerCase to ensure you comparing the same cases, if it's case-insensitive.Westland
you can add JSX use case <input checkbox={jsonResponse.value==="true"?true:false} /> which comes handy in mapping of retrieved json from API in your JSXProfession
S
6

const boolTrue = JSON.parse("true")
const boolFalse = JSON.parse("false")


console.log(boolTrue) // true
console.log(boolFalse) // false

To convert string boolean like "true" to actually boolean value is just wrapping to JSON.parse() example: JSON.parse("true")

Sponger answered 5/11, 2008 at 0:13 Comment(0)
R
6
function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch {
        return false;
    }
}
Remains answered 5/11, 2008 at 0:13 Comment(1)
This is the one I use. Yes you could attempt to widen the net and support more values but how far do you go? So "TRUE" should return true? What about "tRuE". Or "yes". Or "Y". And why stick to just English - maybe the French "oui" should return true?? where does it end? This answer lets javascript itself make the decisionJailhouse
E
6

I wrote a function to match PHP's filter_var which does this nicely. Available in a gist: https://gist.github.com/CMCDragonkai/7389368

/**
 * Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation
 * @param  {Mixed}        value 
 * @param  {Boolean}      nullOnFailure = false
 * @return {Boolean|Null}
 */
var parseBooleanStyle = function(value, nullOnFailure = false){
    switch(value){
        case true:
        case 'true':
        case 1:
        case '1':
        case 'on':
        case 'yes':
            value = true;
            break;
        case false:
        case 'false':
        case 0:
        case '0':
        case 'off':
        case 'no':
            value = false;
            break;
        default:
            if(nullOnFailure){
                value = null;
            }else{
                value = false;
            }
            break;
    }
    return value;
};
Eulogist answered 5/11, 2008 at 0:13 Comment(1)
yours was almost what I was looking for. Here's my variation: ``` function parseBool( value, nullOnFailure = false ) { let value2 = parseFloat( value ) if( !isNaN( value2 )) return !!value2 if( typeof value !== 'string' ) return !!value switch( value.trim().toLowerCase() ) { case 't': case 'true': case 'on': case 'y': case 'yes': return true case 'f': case 'false': case 'off': case 'n': case 'no': return false default: return nullOnFailure ? null : false } } ```Appanage
L
5

The most simple way is

a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;
Lambeth answered 5/11, 2008 at 0:13 Comment(1)
Here's mine function boolify(value = false) { return ["true", "1", "yes", "y", "on"].indexOf(String(value).toLowerCase()) != -1; }Voorhis
S
5

If you are certain that the test subject is always a string, then explicitly checking that it equals true is your best bet.

You may want to consider including an extra bit of code just in case the subject could actually a boolean.

var isTrueSet =
    myValue === true ||
    myValue != null &&
    myValue.toString().toLowerCase() === 'true';

This could save you a bit of work in the future if the code gets improved/refactored to use actual boolean values instead of strings.

Shirring answered 5/11, 2008 at 0:13 Comment(0)
P
5
String(true).toLowerCase() == 'true'; // true
String("true").toLowerCase() == 'true'; // true
String("True").toLowerCase() == 'true'; // true
String("TRUE").toLowerCase() == 'true'; // true

String(false).toLowerCase() == 'true'; // false

If you are not sure of the input, the above works for boolean and as well any string.

Perfunctory answered 5/11, 2008 at 0:13 Comment(1)
Or true.toString()==='true'. Also, why are you making String(true) and String('true') lowercase? lolHintz
G
5

Lots of fancy answers here. Really surprised no one has posted this solution:

var booleanVal = toCast > '';

This resolves to true in most cases other than bool false, number zero and empty string (obviously). You can easily look for other falsey string values after the fact e.g.:

var booleanVal = toCast > '' && toCast != 'false' && toCast != '0';  
Geriatric answered 5/11, 2008 at 0:13 Comment(0)
C
5

I use an own method which includes a check if the object exists first and a more intuitive conversion to boolean:

function str2bool(strvalue){
  return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);
}

The results are:

var test; // false
var test2 = null; // false
var test3 = 'undefined'; // false
var test4 = 'true'; // true
var test5 = 'false'; // false
var test6 = true; // true
var test7 = false; // false
var test8 = 1; // true
var test9 = 0; // false
var test10 = '1'; // true
var test11 = '0'; // false

Fiddle: http://jsfiddle.net/av5xcj6s/

Convertible answered 5/11, 2008 at 0:13 Comment(0)
S
5
function parseBool(value) {
    if (typeof value === "boolean") return value;

    if (typeof value === "number") {
        return value === 1 ? true : value === 0 ? false : undefined;
    }

    if (typeof value != "string") return undefined;

    return value.toLowerCase() === 'true' ? true : false;
}
Spectroscopy answered 5/11, 2008 at 0:13 Comment(1)
For a string, I personnally would have returned true for "true" like you did, but false for "false" only, and undefined otherwise. Sort of what you previously made with the integer case.Jubilate
A
4

It would be great if there was a function on the String object that did this for us, but we can easily add our own prototypes to extend the String object.

Add this code somewhere in your project before you use it.

String.prototype.toBoolean = function() {
   return String(this.valueOf()).toLowerCase() === true.toString();
};

Try it out like this:

var myValue = "false"
console.log("Bool is " + myValue.toBoolean())
console.log("Bool is " + "False".toBoolean())
console.log("Bool is " + "FALSE".toBoolean())
console.log("Bool is " + "TRUE".toBoolean())
console.log("Bool is " + "true".toBoolean())
console.log("Bool is " + "True".toBoolean())

So the result of the original question would then be:

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue.toBoolean();
Abshier answered 5/11, 2008 at 0:13 Comment(1)
Boolean.prototype is fully supported in all browsersAbshier
N
4
/// Convert something to boolean
function toBoolean( o ) {
    if ( null !== o ) {
        let t = typeof o;
        if ( "undefined" !== typeof o ) {
            if ( "string" !== t ) return !!o;
            o = o.toLowerCase().trim();
            return "true" === o || "1" === o;
        }
    }
    return false;
}

toBoolean(false) --> false
toBoolean(true) --> true
toBoolean("false") --> false
toBoolean("true") --> true
toBoolean("TRue") --> true
toBoolean("1") --> true
toBoolean("0") --> false
toBoolean(1) --> true
toBoolean(0) --> false
toBoolean(123.456) --> true
toBoolean(0.0) --> false
toBoolean("") --> false
toBoolean(null) --> false
toBoolean() --> false
Nubbin answered 5/11, 2008 at 0:13 Comment(1)
this is so awesome and useful - thank you so much!Serpigo
A
4

In nodejs by using node-boolify it is possible

Boolean Conversion Results

Boolify(true); //true
Boolify('true'); //true
Boolify('TRUE'); //null
Boolify(1); //true
Boolify(2); //null
Boolify(false); //false
Boolify('false'); //false
Boolify('FALSE'); //null
Boolify(0); //false
Boolify(null); //null
Boolify(undefined); //null
Boolify(); //null
Boolify(''); //null
Allysonalma answered 5/11, 2008 at 0:13 Comment(3)
I'd rather not introduce a new dependency to the project just for converting a string to a boolean.Pusher
It is very light weight and also u can validate whether string is booleanAllysonalma
For such a simple task, a library would not be desirable especially when the library controls how a boolean is defined.Gratia
G
4

I do this, which will handle 1=TRUE=yes=YES=true, 0=FALSE=no=NO=false:

BOOL=false
if (STRING)
  BOOL=JSON.parse(STRING.toLowerCase().replace('no','false').replace('yes','true'));

Replace STRING with the name of your string variable.

If it's not null, a numerical value or one of these strings: "true", "TRUE", "false", "FALSE", "yes", "YES", "no", "NO" It will throw an error (intentionally.)

Gastro answered 5/11, 2008 at 0:13 Comment(1)
JSON.parse is able to handle parsing 'true' and 'false' to Boolean values, so you don't need to wrap it in Boolean().Coaming
F
4

@guinaps> Any string which isn't the empty string will evaluate to true by using them.

How about using the String.match() method

var str="true";
var boolStr=Boolean(str.match(/^true$/i)); 

this alone won't get the 1/0 or the yes/no, but it will catch the TRUE/true, as well, it will return false for any string that happens to have "true" as a substring.

EDIT

Below is a function to handle true/false, 1/0, yes/no (case-insensitive)

​function stringToBool(str) {
    var bool;
    if (str.match(/^(true|1|yes)$/i) !== null) {
        bool = true;
    } else if (str.match(/^(false|0|no)*$/i) !== null) {
        bool = false;
    } else {
        bool = null;
        if (console) console.log('"' + str + '" is not a boolean value');
    }
    return bool;
}

stringToBool('1'); // true
stringToBool('No'); // false
stringToBool('falsey'); // null ("falsey" is not a boolean value.)
stringToBool(''); // false
Fumy answered 5/11, 2008 at 0:13 Comment(1)
As written (on 2018 Dec 19 at 16:00 Z), /^(false|0|no)*$/i will match an empty string (which may be the intent) but also matches any number false, 0, or no, for instance "0falseno0nofalse0" will also evaluate to false but should evaluate to null and output a console message that it is not a Boolean value.Poole
L
4

I've found that using '1' and an empty value '' for boolean values works far more predictably than 'true' or 'false' string values... specifically with html forms since uninitialized/empty values in Dom elements will consistently evaluate to false whereas any value within them evaluates to true.

For instance:

<input type='button' onclick='this.value = tog(this.value);' />

<script type="text/javascript">

    function tog(off) {
        if(off) {
            alert('true, toggle to false');
            return '';
        } else {
            alert('false, toggle to true');
            return '1';
        }
    }   
</script>

Just seemed like an easier road, so far it's been very consistent/easy... perhaps someone can determine a way to break this?

Lindell answered 5/11, 2008 at 0:13 Comment(0)
L
4

If there's some other code that's converting the boolean value to a string, you need to know exactly how that code stores true/false values. Either that or you need to have access to a function that reverses that conversion.

There are infinitely many ways to represent boolean values in strings ("true", "Y", "1", etc.). So you shouldn't rely on some general-purpose string-to-boolean converter, like Boolean(myValue). You need to use a routine that reverses the original boolean-to-string conversion, whatever that is.

If you know that it converts true booleans to "true" strings, then your sample code is fine. Except that you should use === instead of ==, so there's no automatic type conversion.

Lamanna answered 5/11, 2008 at 0:13 Comment(0)
V
3

In typescript, a small function to handle if the value was passed as a string, number or a boolean e.g. 'true', 'false', true, false, 1, or 0.

const getAsBoolean = (value: string | boolean | number) => {
  if (typeof value === 'string') {
    return value === 'true';
  } else if (typeof value === 'boolean' || typeof value === 'number') {
    return Boolean(value);
  } else {
    return undefined;
  }
};
Verbality answered 5/11, 2008 at 0:13 Comment(0)
S
3

Many of the existing answers use an approach that is semantically similar to this, but I think there is value in mentioning that the following "one liner" is often sufficient. For example, in addition to the OP's case (strings in a form) one often wants to read environment variables from process.env in NodeJS (whose values, to the best of my knowledge, are always strings) in order to enable or disable certain behaviors, and it is common for these to have the form SOME_ENV_VAR=1.

const toBooleanSimple = (input) => 
  ['t', 'y', '1'].some(truePrefix => truePrefix === input[0].toLowerCase());

A slightly more robust and expressive implementation might look like this:

/**
 * Converts strings to booleans in a manner that is less surprising
 * to the non-JS world (e.g. returns true for "1", "yes", "True", etc.
 * and false for "0", "No", "false", etc.)
 * @param input
 * @returns {boolean}
 */
function toBoolean(input) {
  if (typeof input !== 'string') {
    return Boolean(input);
  }
  const s = input.toLowerCase();
  return ['t', 'y', '1'].some(prefix => s.startsWith(prefix));
}

A (jest) unit test for this might look like this:

describe(`toBoolean`, function() {
  const groups = [{
    inputs: ['y', 'Yes', 'true', '1', true, 1],
    expectedOutput: true
  }, {
    inputs: ['n', 'No', 'false', '0', false, 0],
    expectedOutput: false
  }]
  for (let group of groups) {
    for (let input of group.inputs) {
      it(`should return ${group.expectedOutput} for ${JSON.stringify(input)}`, function() {
        expect(toBoolean(input)).toEqual(group.expectedOutput);
      });
    }      
  }
});
Standush answered 5/11, 2008 at 0:13 Comment(0)
M
3

Try this solution (it works like a charm!):

function convertStrToBool(str)
    {
        switch(String(str).toLowerCase())
            {
                case 'undefined': case 'null': case 'nan': case 'false': case 'no': case 'f': case 'n': case '0': case 'off': case '':
                    return false;
                    break;
                default:
                    return true;
            };
    };
Mcmillan answered 5/11, 2008 at 0:13 Comment(0)
A
3

For TypeScript we can use the function:

export function stringToBoolean(s: string, valueDefault: boolean = false): boolean {
    switch(s.toLowerCase())
    {
        case "true":
        case "1":
        case "on":
        case "yes":
        case "y":
            return true;

        case "false":
        case "0":
        case "off":
        case "no":
        case "n":
            return false;
    }

    return valueDefault;
}
Alphonso answered 5/11, 2008 at 0:13 Comment(0)
C
3

I'm using this one when I get value from URL/Form or other source.

It is pretty universal one line piece of code.

Maybe not the best for performance, if you need to run it millions times let me know, we can check how to optimize it, otherwise is pretty good and customizable.

boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);

Result:

myVar = true;  // true
myVar = 'true';  // true
myVar = 'TRUE';  // true
myVar = '1';  // true
myVar = 'any other value not related to false';  // true

myVar = false; // false
myVar = 'false';  // false
myVar = 'FALSE';  // false
myVar = '0';  // false
Composure answered 5/11, 2008 at 0:13 Comment(0)
M
3

Here is simple function that will do the trick,

   function convertStringToBool(str){
        return ((str === "True") || (str === "true")) ? true:false;
    }

This will give the following result

convertStringToBool("false") //returns false
convertStringToBool("true") // returns true
convertStringToBool("False") // returns false
convertStringToBool("True") // returns true
Macroscopic answered 5/11, 2008 at 0:13 Comment(2)
wouldn't return str.toLowerCase() === 'true' simpler?Spruce
Ah! you are 100% correct :) . Wrote that answer a few years ago. A better ES6 way of achieving the same result would be: const strToBool = (str) => str.toLowerCase() === 'true'Macroscopic
F
3

Take it easy using this lib.

https://github.com/rohmanhm/force-boolean

you just need to write a single line

const ForceBoolean = require('force-boolean')

const YOUR_VAR = 'false'
console.log(ForceBoolean(YOUR_VAR)) // it's return boolean false

It's also support for following

 return false if value is number 0
 return false if value is string '0'
 return false if value is string 'false'
 return false if value is boolean false
 return true if value is number 1
 return true if value is string '1'
 return true if value is string 'true'
 return true if value is boolean true
Fabrice answered 5/11, 2008 at 0:13 Comment(0)
L
3

I use this simple approach (using "myVarToTest"):

var trueValuesRange = ['1', 1, 'true', true];

myVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);
Littrell answered 5/11, 2008 at 0:13 Comment(0)
G
3

The fastest safe way to convert a string to a boolean in one line of code

One of features that help to fasten the code execution in Javascript is Short-Circuit Evaluation:

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is short-circuit evaluated to false.
  • true || (anything) is short-circuit evaluated to true.

So that if you want to test a string value for being true of false in JSON.parse way of test and keep the performance strong, you may use the || operator to exclude the slow code from execution in case the test value is of boolean type.

test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) > -1

As the Array.prototype.indexOf() method is a part of ECMA-262 standard in the 5th edition, you may need a polyfill for the old browsers support.

// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {

    var k;

    // 1. Let O be the result of calling ToObject passing
    //    the this value as the argument.
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }

    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get
    //    internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If len is 0, return -1.
    if (len === 0) {
      return -1;
    }

    // 5. If argument fromIndex was passed let n be
    //    ToInteger(fromIndex); else let n be 0.
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }

    // 6. If n >= len, return -1.
    if (n >= len) {
      return -1;
    }

    // 7. If n >= 0, then Let k be n.
    // 8. Else, n<0, Let k be len - abs(n).
    //    If k is less than 0, then let k be 0.
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

    // 9. Repeat, while k < len
    while (k < len) {
      // a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the
      //    HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      //    i.  Let elementK be the result of calling the Get
      //        internal method of O with the argument ToString(k).
      //   ii.  Let same be the result of applying the
      //        Strict Equality Comparison Algorithm to
      //        searchElement and elementK.
      //  iii.  If same is true, return k.
      if (k in O && O[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}
Girgenti answered 5/11, 2008 at 0:13 Comment(0)
C
3

Simple solution i have been using it for a while

function asBoolean(value) {

    return (''+value) === 'true'; 

}


// asBoolean(true) ==> true
// asBoolean(false) ==> false
// asBoolean('true') ==> true
// asBoolean('false') ==> false
Callaway answered 5/11, 2008 at 0:13 Comment(0)
J
3

Here is my 1 liner submission: I needed to evaluate a string and output, true if 'true', false if 'false' and a number if anything like '-12.35673'.

val = 'false';

val = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );
Jamshid answered 5/11, 2008 at 0:13 Comment(0)
H
3

i wrote a helper function that handles your cases (and some more). Feel free to alter it to your specific needs

/**
 * @example
 * <code>
 * var pageRequestParams = {'enableFeatureX': 'true'};
 * toBool(pageRequestParams.enableFeatureX);  // returns true
 *
 * toBool(pageRequestParams.enableFeatureY, true, options.enableFeatureY)
 * </code>
 * @param {*}value
 * @param {Boolean}[mapEmptyStringToTrue=false]
 * @param {Boolean}[defaultVal=false] this is returned if value is undefined.
 *
 * @returns {Boolean}
 * @example
 * <code>
 * toBool({'enableFeatureX': ''        }.enableFeatureX);          // false
 * toBool({'enableFeatureX': ''        }.enableFeatureX, true);    // true
 * toBool({                            }.enableFeatureX, true);    // false
 * toBool({'enableFeatureX': 0         }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0'       }.enableFeatureX);          // false
 * toBool({'enableFeatureX': '0 '      }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'false'   }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'falsE '  }.enableFeatureX);          // false
 * toBool({'enableFeatureX': 'no'      }.enableFeatureX);          // false
 *
 * toBool({'enableFeatureX': 1         }.enableFeatureX);          // true
 * toBool({'enableFeatureX': '-2'      }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'true'    }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'false_'  }.enableFeatureX);          // true
 * toBool({'enableFeatureX': 'john doe'}.enableFeatureX);          // true
 * </code>
 *
 */
var toBool = function (value, mapEmptyStringToTrue, defaultVal) {
    if (value === undefined) {return Boolean(defaultVal); }
    mapEmptyStringToTrue = mapEmptyStringToTrue !== undefined ? mapEmptyStringToTrue : false; // default to false
    var strFalseValues = ['0', 'false', 'no'].concat(!mapEmptyStringToTrue ? [''] : []);
    if (typeof value === 'string') {
        return (strFalseValues.indexOf(value.toLowerCase().trim()) === -1);
    }
    // value is likely null, boolean, or number
    return Boolean(value);
};
Hudis answered 5/11, 2008 at 0:13 Comment(0)
P
3
if (String(a) == "true"){
  //true block
} else {
  //false block
}
Praetorian answered 5/11, 2008 at 0:13 Comment(0)
C
2

The shorthand of Boolean(value) is !!value, this is because ! converts a value to the opposite of what it currently is, and then ! reverses it again back to original form.

Cuttlefish answered 5/11, 2008 at 0:13 Comment(0)
F
2
function convertBoolean(value): boolean {
    if (typeof value == 'string') {
        value = value.toLowerCase();
    }
    switch (value) {
        case true:
        case "true":
        case "evet": // Locale
        case "t":
        case "e": // Locale
        case "1":
        case "on":
        case "yes":
        case 1:
            return true;
        case false:
        case "false":
        case "hayır": // Locale
        case "f":
        case "h": // Locale
        case "0":
        case "off":
        case "no":
        case 0:
            return false;
        default:
            return null;
    }
}
Fluidize answered 5/11, 2008 at 0:13 Comment(1)
This sounds too specific. Mind explaining it?Rage
A
2

The strongest way is the following because it also handle undefined case:

    ({'true': true, 'false': false})[myValue];
    ({'true': true, 'false': false})[undefined] // => undefined
    ({'true': true, 'false': false})['true'] // => true
    ({'true': true, 'false': false})['false] // => false
Alyciaalyda answered 5/11, 2008 at 0:13 Comment(1)
What do we say this type of function ?Fung
S
2

WARNING: Never use this method for untrusted input, such as URL parameters.

You can use the eval() function. Directly pass your string to eval() function.

console.log(eval('true'), typeof eval('true'))
console.log(eval('false'), typeof eval('false'))
Sandry answered 5/11, 2008 at 0:13 Comment(2)
There are so many more performant and safer ways to do this.Gomulka
This isn't a recommended solution. Read more - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Bisayas
A
2

Take care, maybe in the future the code change and return boolean instead of one string at the moment.

The solution would be:

//Currently
var isTrue = 'true';
//In the future (Other developer change the code)
var isTrue = true;
//The solution to both cases
(isTrue).toString() == 'true'
Avatar answered 5/11, 2008 at 0:13 Comment(0)
P
2

To evaluate both boolean and boolean-like strings like boolean I used this easy formula:

var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');

As is apparent, it will return true for both true and 'true'. Everything else returns false.

Parvenu answered 5/11, 2008 at 0:13 Comment(0)
N
2

A shorter way to write this, could be var isTrueSet = (myValue === "true") ? true : false; Presuming only "true" is true and other values are false.

Nga answered 5/11, 2008 at 0:13 Comment(1)
If you wanted it short why not writing just var isTrueSet = myValue === "true"; ?Staphylorrhaphy
D
2

A lot of the existing answers are similar, but most ignore the fact that the given argument could also be an object.

Here is something I just whipped up:

Utils.parseBoolean = function(val){
    if (typeof val === 'string' || val instanceof String){
        return /true/i.test(val);
    } else if (typeof val === 'boolean' || val instanceof Boolean){
        return new Boolean(val).valueOf();
    } else if (typeof val === 'number' || val instanceof Number){
        return new Number(val).valueOf() !== 0;
    }
    return false;
};

...and the unit test for it

Utils.Tests = function(){
    window.console.log('running unit tests');

    var booleanTests = [
        ['true', true],
        ['false', false],
        ['True', true],
        ['False', false],
        [, false],
        [true, true],
        [false, false],
        ['gibberish', false],
        [0, false],
        [1, true]
    ];

    for (var i = 0; i < booleanTests.length; i++){
        var lhs = Utils.parseBoolean(booleanTests[i][0]);
        var rhs = booleanTests[i][1];
        var result = lhs === rhs;

        if (result){
            console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\t : \tpass');
        } else {
            console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\t : \tfail');
        }
    }
};
Demented answered 5/11, 2008 at 0:13 Comment(0)
V
2
    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     }; 
Vole answered 5/11, 2008 at 0:13 Comment(0)
T
2

Building on Steven's answer above, I wrote this function as a generic parser for string input:

parse:
  function (value) {
    switch (value && value.toLowerCase()) {
      case null: return null;
      case "true": return true;
      case "false": return false;
      default: try { return parseFloat(value); } catch (e) { return value; }
    }
  }
Tumescent answered 5/11, 2008 at 0:13 Comment(0)
D
2

I've been using this snippet to convert Numbers and Booleans:

var result = !isNaN(value) ? parseFloat(value) : /^\s*(true|false)\s*$/i.exec(value) ? RegExp.$1.toLowerCase() === "true" : value;
Disproportionation answered 5/11, 2008 at 0:13 Comment(0)
M
1

If you have no shame:

String.prototype.toTruth = function () {
    const value = this.valueOf();
    return value === 'true' ? true : value === 'false' ? false : undefined;
};

'true'.toTruth()    // true
'false'.toTruth()   // false
'falsest'.toTruth() // undefined
''.toTruth()        // undefined

(Disclaimer: For the love of ECMA, don't do this.)

It's an interesting question, though, with more repercussions than one might expect.

I called it toTruth and not toBoolean because its return value can't always be a Boolean. One could argue that '' should return false, but what about other strings? Is it true or false?

Unless you use strict typing everywhere, with a 'true' | 'false' union, there's no guarantee that your string is going to contain either true or false (or nothing). So logically, you have to allow for a third value, undefined. (Or throw an error? No thanks.)

This means it actually becomes ternary logic, where undefined is similar to SQL's NULL (neither true nor false). That makes it much more complicated than a simple true/false predicate. Especially when you add JavaScript's truthiness to the equation, where an undefined value might be evaluated as false (falsy).

If you have no shame and actually want to use this (dear god), you should explicitly check against the value you want with === and not use negation (unless you know what you're doing, keep in mind that it's ternary logic):

const input = 'foo'; // or anything else but 'true' or 'false'

input.toTruth()                // undefined

!input.toTruth()               // true (misleading, it's not false)
input.toTruth() !== true       // true (misleading, it's not false)

input.toTruth() === false      // false (correct)
input.toTruth() === true       // false (correct)
input.toTruth() === undefined  // true (correct)

I like JavaScript and I like ternary logic. But carelessly combining the two is a recipe for disaster.

A statically typed language like TypeScript does make it a lot easier. However, the same caveats apply when your code is exposed to code or input you don't control.

type BooleanString = 'true' | 'false'

function toBoolean(predicate: BooleanString): boolean {
    return predicate === 'true';
}

function toTruth(predicate: string): boolean | undefined {
    return predicate === 'true' ? true : predicate === 'false' ? false : undefined;
}
Mercorr answered 5/11, 2008 at 0:13 Comment(0)
H
1

The easiest way of doing this, especially if you're getting the 'true' or 'false' from an input type of radio ie

     <input type='radio' name='IsAllowedToWork' value={true} onChange{handleChange} />

     <input type='radio' name='IsAllowedToWork' value={false} onChange{handleChange} />

is this

    const handleChange = (e) => {
      let { value ,type} = e.target;
      if (type==='radio') {
       value = JSON.parse(value);
      } else if (type === 'file') {
       value = e.target.files[0];
      }  
     setValues({ ...values, [e.target.name]: value });
    };
Heidyheifer answered 5/11, 2008 at 0:13 Comment(1)
For radio buttons, you should use .checkedGibeonite
H
1
function parseBool(value: any, defaultsOnUndefined?: boolean) {
  if (['true', true, 1, '1', 'yes'].includes(value)) {
    return true;
  }
  if (['false', false, 0, '0', 'no', null].includes(value)) {
    return false;
  }
  return defaultsOnUndefined;
}

OR

function parseBool(value: any) {
  if (['true', true, 1, '1', 'yes'].includes(value)) {
    return true;
  }
  return false;
}
Hagridden answered 5/11, 2008 at 0:13 Comment(0)
H
1

ES6+

const string = "false"
const string2 = "true"

const test = (val) => (val === "true" || val === "True")
console.log(test(string))
console.log(test(string2))
Higgs answered 5/11, 2008 at 0:13 Comment(3)
Pass "True" to this and it returns falseVeg
@Veg ok, i minded this and created a fix.Higgs
val.toLowerCase() === "true"Betthezul
B
1

if you are sure the input is anything only within 'true' and 'false' why not :

let x = 'true' ;
//let x = 'false';
let y = x === 'true' ? true : false;
console.log(typeof(y), y);
Burin answered 5/11, 2008 at 0:13 Comment(1)
same as y= (x=='true');Hyperdulia
O
1

I think it can be done in 1 liner with a use arrow function

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

You guys can run and test various cases with following code snippet

const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;

console.log(convertStringToBoolean("a"));
console.log(convertStringToBoolean(null));
console.log(convertStringToBoolean(undefined));
console.log(convertStringToBoolean("undefined"));
console.log(convertStringToBoolean(true));
console.log(convertStringToBoolean(false));
console.log(convertStringToBoolean(0));
console.log(convertStringToBoolean(1)); // only case which will not work
Oviposit answered 5/11, 2008 at 0:13 Comment(0)
A
1

You don't even need to use a variable, if you know that 'true' will always be lowercase you can use this which will return true or false:

(eval(yourBooleanString == 'true'))
Ambages answered 5/11, 2008 at 0:13 Comment(1)
It should be noted that using eval for trivial cases like this is NOT RECOMMENDED. Read this developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Bisayas
S
1

Use an if statment:

function parseBool(str) {
  if (str.toLowerCase() == 'true') {
    var val = true;
  } else if (str.toLowerCase() == 'false') {
    var val = false;
  } else {
    //If it is not true of false it returns undefined.//
    var val = undefined;
  }
  return val;
}
console.log(parseBool(''), typeof parseBool(''));
console.log(parseBool('TrUe'), typeof parseBool('TrUe'));
console.log(parseBool('false'), typeof parseBool('false'));
Sandry answered 5/11, 2008 at 0:13 Comment(0)
A
1
const result: Boolean = strValue === "true" ? true : false
Admonitory answered 5/11, 2008 at 0:13 Comment(0)
P
1

In HTML the values of attributes eventually become strings. To mitigate that in undesired situations you can have a function to conditionally parse them into values they represent in the JavaScript or any other programming langauge of interest.

Following is an explanation to do it for reviving boolean type from the string type, but it can be further expanded into other data types too, like numbers, arrays or objects.

In addition to that JSON.parse has a revive parameter which is a function. It also can be used to achieve the same.

Let's call a string looking like a boolean, "true", a boolean string likewise we can call a string like a number, "1", a number string. Then we can determine if a string is a boolean string:

const isBooleanString = (string) => ['true', 'false'].some(item => item === string);

After that we need to parse the boolean string as JSON by JSON.parse method:

JSON.parse(aBooleanString);

However, any string that is not a boolean string, number string, or any stringified object or array (any invalid JSON) will cause the JSON.parse method to throw a SyntaxError.

So, you will need to know with what to call it, i.e. if it is a boolean string. You can achieve this by writing a function that makes the above defiend boolean string check and call JSON.parse:

function parse(string){
  return isBooleanString(string) ? JSON.parse(string)
    : string;
}

One can further generalize the isBooleanString utility to have a more broader perspective on what qualifies as a boolean string by further parametrizing it to accept an optional array of accepted boolean strings:

const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);
Perish answered 5/11, 2008 at 0:13 Comment(0)
H
1

I hope this is a most comprehensive use case

function parseBoolean(token) {
  if (typeof token === 'string') {
    switch (token.toLowerCase()) {
      case 'on':
      case 'yes':
      case 'ok':
      case 'ja':
      case 'да':
      // case '':
      // case '':
        token = true;
        break;
      default:
        token = false;
    }
  }
  let ret = false;
  try {
    ret = Boolean(JSON.parse(token));
  } catch (e) {
    // do nothing or make a notification
  }
  return ret;
}
Hardened answered 5/11, 2008 at 0:13 Comment(0)
P
1

Convert String to Boolean

var vIn = "true";
var vOut = vIn.toLowerCase()=="true"?1:0;

Convert String to Number

var vIn = 0;
var vOut = parseInt(vIn,10/*base*/);
Pirzada answered 5/11, 2008 at 0:13 Comment(0)
P
1
var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1) ? true : false;

or even just

var trueVals = ["y", "t", "yes", "true", "gimme"];
var isTrueSet = (trueVals.indexOf(myValue) > -1);

Similar to some of the switch statements but more compact. The value returned will only be true if the string is one of the trueVals strings. Everything else is false. Of course, you might want to normalise the input string to make it lower case and trim any spaces.

Poignant answered 5/11, 2008 at 0:13 Comment(0)
K
1

To Get Boolean values from string or number Here is good solution:

var boolValue = Boolean(Number('0'));

var boolValue = Boolean(Number('1'));

First will return false and second will return true.

Kareenkarel answered 5/11, 2008 at 0:13 Comment(0)
D
1

You even do not need to convert the string to boolean. just use the following: var yourstring = yourstringValue == 1 ? true : false;

Djerba answered 5/11, 2008 at 0:13 Comment(0)
G
1

Boolean.parse() does exist in some browser implementations. It's definitely not universal, so if that's something that you need than you shouldn't use this method. But in Chrome, for example (I'm using v21) it works just fine and as one would expect.

Grebe answered 5/11, 2008 at 0:13 Comment(1)
Boolean("false") => trueKatleen
C
1
function returnBoolean(str){

    str=str.toString().toLowerCase();

    if(str=='true' || str=='1' || str=='yes' || str=='y' || str=='on' || str=='+'){
        return(true);
    }
    else if(str=='false' || str=='0' || str=='no' || str=='n' || str=='off' || str=='-'){
        return(false);
    }else{
        return(undefined);
    }
}
Crude answered 5/11, 2008 at 0:13 Comment(0)
T
0
const booleanOfsomeVal = someVal == "1" || someVal == "true";

This should work in typescript & javascript both

considering someVal could have possible values

0/1/"0"/"1"/true/false/"true"/"false"/undefined/null/NaN

Thalamus answered 5/11, 2008 at 0:13 Comment(0)
I
0

Using lodash:

import _ from 'lodash';

const toBoolean = (val) => _.isEqual(_.toLower(val), 'true');

const values = [0, 1, '', undefined, null, [], {}, new Date(), true, false, 'true', 'false', 'True', 'False'];

_.forEach(values, (value) => {
    console.log(`${value} : ${toBoolean(value)}`);
});

https://replit.com/@tokra1/toBoolean-w-Lodash?v=1

enter image description here

Irksome answered 5/11, 2008 at 0:13 Comment(0)
L
0

If you are using Environment Variables, use the following. Works on Heroku. Environment variables are string values that has to be converted to boolean values.

// Create the database connection
    this.connection = new Sequelize({
      username: process.env.PG_USERNAME,
      password: process.env.PG_PASSWORD,
      database: process.env.PG_DATABASE,
      host: process.env.PG_HOST,
      port: process.env.PG_PORT,
      dialect: process.env.PG_DIALECT,
      dialectOptions: {
        ssl: {
          require: process.env.PG_DIALECT_OPTION_SSL_REQUIRED === 'true', // <<< convert from string to bool
          rejectUnauthorized:
            process.env.PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED === 'true', // <<< convert from string to bool
        },
      },
      logging: true,
    });

env file

# PostgreSQL Config
PG_USERNAME=ttubkcug
PG_PASSWORD=ea59cee2883e73c602e6c05b674cf16950d6a9f05ab
PG_DATABASE=d67potesdliv25
PG_HOST=ec2-23-333-45-192.compute-1.amazonaws.com
PG_PORT=5432
PG_DIALECT=postgres
PG_DIALECT_OPTION_SSL_REQUIRED=true
PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED=false
Lilias answered 5/11, 2008 at 0:13 Comment(1)
This answer does not seem to address the original question in any way.Varhol
C
0

The `toBoolean' function returns false for null, undefined, '', 'false'. It returns true for any other string:

const toBoolean = (bool) => {
  if (bool === 'false') bool = false
  return !!bool
}

toBoolean('false') // returns false
Consols answered 5/11, 2008 at 0:13 Comment(3)
So it would return true for "False", would it not?Anguilliform
@OskarBerggren It wouldn't. Look at the code, if (bool === 'false') bool = false then, when it runs return !!bool it's returning !!false which is false.Sandry
@JustinLiu jsfiddle certainly evaluates toBoolean('False') to true which I think is probably not a good idea. With respect to the actual question, which was about a string representing a boolean value, I frankly think it's a bad idea to return true for "any "other" "random" "string" - it should raise an error instead of assuming that a caller that sent an erroneous string is happy with having that interpreted as true.Anguilliform
A
0

The following would be enough

String.prototype.boolean = function() {
    return "true" == this; 
};

"true".boolean() // returns true "false".boolean() // returns false
Autacoid answered 5/11, 2008 at 0:13 Comment(3)
Modifying the prototype is very bad ideaDendroid
@SzymonWygnański: i disagree. I do not see any other reason apart from for--in loop and native support for the same functionality by browsers. Reg for-inloop: i cannot think of a case, where for-in loops are really needed in string. Reg native support: we can definitely add a proto prop until native browsers support, if we are not building a framework like - prototype or jquery, etc... More about this by @Kangax(Perfection kills) is here. webcache.googleusercontent.com/…Autacoid
Consider: we can go even farther: "true".checkbox() would convert to checkbox, or "true".application() would convert to app:D Not only for-in loops fail but the style is wrong here. Where would you look for the code of this "boolean/checkbox/application" definition in a big app? Imagine world where every library would do thinks like that. Isn't it much better to define a class or function: checkbox("true") - it's just cleaner and almost the same amount of letters. You never know IF browsers will support your custom function until it's defined as a standard (like Object.create etc...).Dendroid
O
-1

I needed a code that converts any variable type into Boolean. Here's what I came up with:

const toBoolean = (x) => {
    if (typeof x === 'object') {
      for (var i in x) return true
      return false
    }
    return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())
  }

Let's test it!

const toBoolean = (x) => {
    if (typeof x === 'object') {
      for (var i in x) return true
      return false
    }
    return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())
  }
  

  // Let's test it!
  let falseValues = [false, 'False', 0, '', 'off', 'no', [], {}, null, undefined]
  let trueValues = [  true, 'true', 'True', 1, -1, 'Any thing', ['filled array'], {'object with any key': null}]
  
  falseValues.forEach((value, index) => console.log(`False value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`))
  trueValues.forEach((value, index) => console.log(`True value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`))

You can remove words like "off" and "no" from the array if they don't match your case.

Outdo answered 5/11, 2008 at 0:13 Comment(0)
W
-1

Simple one line operation if you need Boolean false and true from the string values:

storeBooleanHere = stringVariable=="true"?true:false;
  • storeBooleanHere - This variable will hold the boolean value
  • stringVariable - Variable that has boolean stored as string
Weinberger answered 5/11, 2008 at 0:13 Comment(1)
simplified version: storeBooleanHere = stringVariable.toLowerCase() !== 'false' ;Marvelofperu
H
-1

You can use Function to return a Boolean value from string "true" or "false"

const TRUE_OR_FALSE = str => new Function(`return ${str}`)();

const [TRUE, FALSE] = ["true", "false"];

const [T, F] = [TRUE_OR_FALSE(TRUE), TRUE_OR_FALSE(FALSE)];

console.log(T, typeof T); // `true` `"boolean"`

console.log(F, typeof F); // `false` `"boolean"`
Hyphen answered 5/11, 2008 at 0:13 Comment(7)
That has the same issues (with security and performance) as evalGibeonite
There's no issues using eval(), it's part of the JavaScript programming language specified in ECMA-262.Hyphen
That's just ignorant/naive. Bad performance and content security policy restrictions are definitely issues with this solution.Gibeonite
I am neither ignorant nor naive. I know what I'm doing when I use Function() and/or eval(). You are talking about imaginary issues that don't exist. I'm my own browser I can get around any and all CSP, COEP, COOP, CORP, CORS to achieve my aims.Hyphen
@Gibeonite When you use Ecmascript import you are literally executing code that you have no idea what is contained therein unless you wrote the code. So if you are going to be talking about Function() and eval() understand you are talking about Ecmascript import in the same way - that further remains a two-way binding after initial execution.Hyphen
Well great if you can achieve your own aims with your own code in your own browser. That doesn't make it a good answer for everyone to use. Especially when trying to convert arbitrary strings of unknown provenance to booleans.Gibeonite
Sure it's a good answer. It's a tool in the JavaScript programming language tool box. It's no different from using Ecmascript Modules import for code you didn't write.Hyphen
R
-2

The simplest way to convert a string to a boolean is the following:

Boolean(<stringVariable>)
Redhead answered 5/11, 2008 at 0:13 Comment(1)
Boolean("false") === true // output trueMarvelofperu
A
-3

var isTrueSet = eval(myValue);

Auditory answered 5/11, 2008 at 0:13 Comment(0)
L
-5

works perfectly and very simple:

var boolean = "false";
boolean = (boolean === "true");

//boolean = JSON.parse(boolean); //or this way.. 

to test it:

var boolean = "false";
boolean = (boolean === "true");

//boolean = JSON.parse(boolean); //or this way.. 

if(boolean == true){
    alert("boolean = "+boolean);
}else{
    alert("boolean = "+boolean);
}
Loxodromics answered 5/11, 2008 at 0:13 Comment(5)
my bad i have fixed the above snippet - works now. not sure how those inverted commas "" got in there! ;/ @HugoZapataDonnell
But the question is, how to convert a string to boolean. new Boolean("false") doesn't work, so your answer is not correct.Slugabed
@HugoZapata updated the answer, yes was incorrect (but strangely was working before) updated answer works correctly now.Donnell
What is the point of the if/else? You are alert'ing the same thing in both branches.Labour
@Labour because if boolean == false, then you can do something different in the else statement - the alert is just an example. even though its the same it outputs something different if the boolean var = true/false.Donnell
G
-6

// Try this in two ways convert a string to boolean

    const checkBoolean = Boolean("false"); 
    const checkBoolean1 = !!"false";  
    
    console.log({checkBoolean, checkBoolean1});  
Garlicky answered 5/11, 2008 at 0:13 Comment(1)
Isn't Boolean("false") returns trueAmorete
L
-7

Possible ways to convert String to Boolean I recommend you to create a function like the third option in the image and place it in a helper class as export, and reuse this function when you need.

Lavoie answered 5/11, 2008 at 0:13 Comment(2)
Downvoted because you posted an image of the code rather than the code itself.Monreal
@Monreal you failed to mention that presentation is nice.Capitulate
E
-25

Just do a:

var myBool = eval (yourString);

Examples:

alert (eval ("true") == true); // TRUE
alert (eval ("true") == false); // FALSE
alert (eval ("1") == true); // TRUE
alert (eval ("1") == false); // FALSE
alert (eval ("false") == true); // FALSE;
alert (eval ("false") == false); // TRUE
alert (eval ("0") == true); // FALSE
alert (eval ("0") == false); // TRUE
alert (eval ("") == undefined); // TRUE
alert (eval () == undefined); // TRUE

This method handles the empty string and undefined string naturally as if you declare a variable without assigning it a value.

Elsieelsinore answered 5/11, 2008 at 0:13 Comment(2)
-1: Please don't advocate the use of eval (except perhaps for clever hacks and necessity).Prehensile
that's a really bad and insecure use of eval. and it's not even clever. -1Fado

© 2022 - 2024 — McMap. All rights reserved.