3459

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?

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Kevin
  • 7,856
  • 11
  • 35
  • 40
  • 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. – yurisich Nov 10 '13 at 17:56
  • Possible duplicate of http://stackoverflow.com/questions/263965 – Rodrigo Siqueira Nov 11 '13 at 11:56
  • @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. – Nope Apr 24 '14 at 16:19
  • 104
    "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);` – Mark K Cowan Apr 16 '15 at 10:25
  • 14
    Easily handle strings and bools: `function parseBool(val) { return val === true || val === "true" }` – WickyNilliams Sep 10 '15 at 14:24
  • 3
    @Mark `function checkBool(x) { if(x) {return true;} else {return false;} }` – Sebi Nov 29 '16 at 15:10
  • 4
    @Sebi: You forgot to document it: `if (checkBool(x) != false) { ... } else { ... }` – Mark K Cowan Nov 29 '16 at 18:21
  • 9
    `!!(parseInt(value) || value === "true")` – iamandrewluca Feb 22 '17 at 03:58
  • You can't, it is impossible! – vitaly-t Oct 06 '19 at 19:47
  • 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 operator – Agnius Vasiliauskas Dec 11 '19 at 14:39
  • 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') => true` – Milos Radojevic Feb 09 '20 at 10:06
  • `!myVar.slice(4,5);` `myVar = 'TRUE' // true` `myVar = 'FALSE' // false` – ZenAtWork Jul 17 '20 at 16:15
  • @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. – danbars Jan 28 '21 at 05:48
  • `toBool ={'false':false,'true':true } invertBool = {'false':true,'true':false}` can be used `toBool[string]` – varun sharma May 06 '21 at 05:10
  • JSON.parse('true') is the most easiest way to convert to boolean – Deepak paramesh Jul 29 '21 at 20:56
  • 'true' === true is false – Haris Sep 16 '22 at 09:32
  • 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. – user2620460 May 07 '23 at 00:20

104 Answers104

4892

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.

ADTC
  • 8,999
  • 5
  • 68
  • 93
guinaps
  • 4,051
  • 1
  • 17
  • 8
  • 247
    `myValue === 'true';` is precisely equivalent to `myValue == 'true';`. There is no benefit in using `===` over `==` here. – Tim Down Aug 26 '10 at 11:01
  • 737
    I follow [Crockford's advice](http://javascript.crockford.com/code.html) and use `===` and `!==` whenever it makes sense, which is almost always. – guinaps Feb 10 '11 at 15:37
  • @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. – June Dec 07 '21 at 18:35
  • 5
    `===` should be used because it's also checking for the right type. Also, it has better comparison performances than `==`. – NoxFly Dec 18 '21 at 11:20
  • 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; – Max Waterman Jan 27 '22 at 03:13
  • 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))` – Iglesias Leonardo Mar 13 '22 at 15:36
  • 2
    Thanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans. – Jose Quijada Apr 12 '22 at 03:29
  • 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. – Elijah Lynn Jun 02 '22 at 18:06
849

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());
Alex
  • 14,104
  • 11
  • 54
  • 77
Luke
  • 1,471
  • 3
  • 12
  • 11
  • 80
    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. – BishopZ Jan 26 '13 at 22:52
  • 55
    It's pretty simple to just say `JSON.parse("TRUE".toLowerCase())` so that it can parse correctly. – Yuck Aug 08 '13 at 15:00
  • 3
    @BishopZ : Stopping JS execution is probably a desirable feature following best-pattern coding styles: https://en.wikipedia.org/wiki/Fail-fast – earizon Oct 13 '21 at 10:04
  • 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 :) – Eve Apr 30 '22 at 13:03
  • Careful with `JSON.parse` as it is one of the source of DOM-based client-side JSON injection. https://portswigger.net/web-security/dom-based/client-side-json-injection – Ravi MCA Oct 04 '22 at 11:41
  • @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. – Auspex Oct 28 '22 at 15:21
297
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);
    }
}
jhpg
  • 397
  • 3
  • 9
  • 56
    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;}` – Robert Jun 25 '13 at 05:27
  • 6
    Note, this will default to `true` - for example: `stringToBoolean('banana') // true` – dav_i Jul 07 '21 at 13:25
  • 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...). – Stefan Steiger Sep 15 '22 at 09:48
  • 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` – Andrew Oct 27 '22 at 19:28
260

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
Daniel_Kamel
  • 610
  • 8
  • 29
  • 25
    When you can receive a string in uppercase or a boolean, then `String(a).toLowerCase() === 'true'` – pauloya Feb 29 '12 at 12:49
170

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.

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
148

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);
fraxture
  • 5,113
  • 4
  • 43
  • 83
Deepak paramesh
  • 495
  • 1
  • 8
  • 19
134

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)

shrewmouse
  • 5,338
  • 3
  • 38
  • 43
Shadow2531
  • 11,980
  • 5
  • 35
  • 48
  • 10
    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. – Shadow2531 Jul 16 '11 at 19:06
  • 42
    @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`. – devios1 Sep 12 '11 at 14:29
  • 1
    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". – hargobind Feb 21 '22 at 00:03
  • 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. – wybe Jul 05 '22 at 08:27
79

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]));}
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • 1
    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: – earizon Oct 13 '21 at 10:15
  • @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. – Stefan Steiger Sep 15 '22 at 09:32
  • 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. https://www.google.com/search?channel=fs&q=billion+dollar+mistake (100% agree about using strict mode) – earizon Sep 16 '22 at 11:27
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

BrDaHa
  • 5,138
  • 5
  • 32
  • 47
45

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/

Jan Remunda
  • 7,840
  • 8
  • 51
  • 60
  • 1
    The 'without JSON' version has some flaw: val="0" ; console.log(!!(+val||String(val).toLowerCase().replace(!!0,'')) ); produces true – Etienne Jul 22 '14 at 07:42
  • 4
    `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,'')); } – Ron Martinez Aug 21 '14 at 13:25
36

Your solution is fine.

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

Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
  • 21
    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: http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use/359509#359509 – Mariano Desanze Aug 17 '10 at 19:01
  • 4
    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. – Robert Jun 25 '13 at 05:49
  • 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. – ixpl0 Feb 06 '23 at 13:04
32

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.

yunzen
  • 32,854
  • 11
  • 73
  • 106
thdoan
  • 18,421
  • 1
  • 62
  • 57
  • 1
    To understand what's "wrong" (or right) with eval - check out articles like http://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/ or search on stackoverflow for 'Javascript eval malware' – GrahamMc Nov 22 '12 at 08:52
  • 3
    I agree that `var isTrueSet = (myValue === 'true');` is the best answer. – thdoan Jan 28 '13 at 07:35
  • I like that it's concise. But it fails spectacularly for the basic case of `eval('TRUE')`; proving once again, that `eval()` is evil. – Snowman Aug 06 '15 at 09:41
  • @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;` – thdoan Aug 07 '15 at 06:10
  • 1
    @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. – Snowman Aug 07 '15 at 06:30
  • 4
    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().` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! – Shubham Chaudhary Jan 18 '21 at 15:20
31
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());
Prestaul
  • 83,552
  • 10
  • 84
  • 84
  • 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};` – Bernesto Apr 07 '23 at 00:29
23

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.

Community
  • 1
  • 1
sospedra
  • 14,238
  • 3
  • 21
  • 32
20

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');
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
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".

zobier
  • 1,579
  • 2
  • 13
  • 11
18

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
Felipe Chernicharo
  • 3,619
  • 2
  • 24
  • 32
  • 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` – ksugiarto Jun 02 '21 at 20:11
  • 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 – Felipe Chernicharo Jun 02 '21 at 22:15
  • Ah sorry! My bad, I was testing the first function instead. Thanks for clarifying this. – ksugiarto Jun 03 '21 at 15:38
  • Your examples are all strings. For example `'null'` is not actual `null`, it's a string with characters `null` in it. – ADTC Feb 16 '23 at 07:20
17

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
AndreasPizsa
  • 1,736
  • 19
  • 26
16

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

Vivek
  • 1,465
  • 14
  • 29
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.");
  }
};
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
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
Sandip Nirmal
  • 2,283
  • 21
  • 24
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, '').

  • 1
    hmm, this is perfect – prabhatojha Dec 28 '21 at 08:13
  • 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:''}` – stu0292 Jan 22 '22 at 00:47
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"
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
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)));
user1063287
  • 10,265
  • 25
  • 122
  • 218
pankaj sharma
  • 286
  • 2
  • 11
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
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
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"
Adam Pietrasiak
  • 12,773
  • 9
  • 78
  • 91
  • 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.prototype`to use this wherever we want it? – MarceloBarbosa Feb 09 '15 at 18:40
  • 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. ;) – cassi.lup Mar 11 '15 at 10:30
  • 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 } – bortunac Dec 02 '15 at 11:48
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
Yohan
  • 379
  • 1
  • 5
  • 14
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. :-)

staticsan
  • 29,935
  • 4
  • 60
  • 73
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
> 
vbranden
  • 5,814
  • 2
  • 22
  • 15
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;
  }
}
imjustmatthew
  • 176
  • 1
  • 3
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..
Dead.Rabit
  • 1,965
  • 1
  • 28
  • 46
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;
OhkaBaka
  • 339
  • 6
  • 15
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!

risingfish
  • 31
  • 1
  • 1
  • 4
    What conversion were you talking about? :-) – YMMD May 18 '12 at 00:41
  • 2
    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 http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use – ars265 Dec 28 '12 at 15:40
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!

BishopZ
  • 6,269
  • 8
  • 45
  • 58
  • 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. – JMTyler May 09 '13 at 18:27
  • `return /^(true|yes|1|t|y)$/i.test(str);` – Kevin Boucher Jul 08 '16 at 20:10
7

The simplest way which I always use:

let value = 'true';
let output = value === 'true';
Josh Wood
  • 461
  • 3
  • 14
panatoni
  • 735
  • 6
  • 13
  • 4
    Ternary operator is not necesary. Only with let output = value === 'true' works. – zeross Jun 06 '19 at 08:05
  • 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? – panatoni Jun 07 '19 at 12:59
  • 1
    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. – zeross Jun 07 '19 at 13:35
  • 1
    Yeah sure you are right, I edited my answered - my fault ;] – panatoni Aug 16 '19 at 21:03
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;
};
CMCDragonkai
  • 6,222
  • 12
  • 56
  • 98
  • 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 } } ``` – royce3 Jan 31 '22 at 18:43
6
function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch {
        return false;
    }
}
kiwichris
  • 319
  • 1
  • 3
  • 10
ecabuk
  • 1,641
  • 1
  • 18
  • 20
  • 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 decision – kiwichris Nov 07 '22 at 08:43
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")

Sigit
  • 728
  • 7
  • 12
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;
}
Cliff Mayson
  • 483
  • 5
  • 15
  • 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. – Pierre-Adrien Mar 24 '15 at 17:06
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/

Timo Ernst
  • 15,243
  • 23
  • 104
  • 165
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';  
benipsen
  • 493
  • 6
  • 12
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.

Chanakya Vadla
  • 3,019
  • 2
  • 22
  • 24
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.

Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
Al Albers
  • 49
  • 2
  • 5
5

The most simple way is

a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;
Alon Bar
  • 482
  • 9
  • 10
Faizan Khan
  • 19
  • 1
  • 3
  • Here's mine `function boolify(value = false) { return ["true", "1", "yes", "y", "on"].indexOf(String(value).toLowerCase()) != -1; }` – Patrick Matte May 01 '20 at 18:59
5

Dead-simple, best performing and strict

Best performance according to https://stackoverflow.com/a/28588344/7333766

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')
}
Eli O.
  • 1,543
  • 3
  • 18
  • 27
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
Scrimothy
  • 2,536
  • 14
  • 23
  • 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. – Zarepheth Dec 19 '18 at 16:02
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.)

konsumer
  • 3,411
  • 1
  • 30
  • 31
  • `JSON.parse` is able to handle parsing 'true' and 'false' to Boolean values, so you don't need to wrap it in `Boolean()`. – whitfin Jan 27 '15 at 10:52
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.

JW.
  • 50,691
  • 36
  • 115
  • 143
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
Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54
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
cskwg
  • 790
  • 6
  • 13
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();
Richard Torcato
  • 2,504
  • 25
  • 26
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?

hajikelist
  • 1,136
  • 9
  • 9
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);
};
dalimian
  • 2,066
  • 1
  • 12
  • 6
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 );
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
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
Mahes
  • 3,938
  • 1
  • 34
  • 39
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;
  };
}
Community
  • 1
  • 1
Eugene Tiurin
  • 4,019
  • 4
  • 33
  • 32
3

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

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

myVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);
jose.serapicos
  • 580
  • 5
  • 10
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
Rohman HM
  • 2,539
  • 3
  • 25
  • 40
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
Dayem Siddiqui
  • 175
  • 2
  • 11
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
Kostanos
  • 9,615
  • 4
  • 51
  • 65
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;
}
Yuriy Litvin
  • 101
  • 2
  • 3
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;
            };
    };
James Anderson Jr.
  • 760
  • 1
  • 8
  • 26
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);
      });
    }      
  }
});
jacobq
  • 11,209
  • 4
  • 40
  • 71
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;
  }
};
Abba
  • 334
  • 5
  • 9
3
if (String(a) == "true"){
  //true block
} else {
  //false block
}
Swift
  • 13,118
  • 5
  • 56
  • 80
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;
jerone
  • 16,206
  • 4
  • 39
  • 57
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; }
    }
  }
jackvsworld
  • 1,453
  • 15
  • 17
2
    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     }; 
Andreas Dyballa
  • 179
  • 1
  • 5
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');
        }
    }
};
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
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.

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.

Martin Malinda
  • 1,573
  • 11
  • 20
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'
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
jdnichollsc
  • 1,520
  • 1
  • 24
  • 44
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'))
D. Pardal
  • 6,173
  • 1
  • 17
  • 37
ritesh
  • 177
  • 2
  • 4
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
Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
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;
    }
}
OMANSAK
  • 1,066
  • 1
  • 12
  • 30
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.

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.

mbeasley
  • 4,864
  • 5
  • 27
  • 39
1

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

purab
  • 211
  • 1
  • 3
  • 9
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.

Siten
  • 4,515
  • 9
  • 39
  • 64
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.

Steve Mc
  • 3,433
  • 26
  • 35
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*/);
Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25
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;
}
olegtaranenko
  • 3,722
  • 3
  • 26
  • 33
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);
sçuçu
  • 2,960
  • 2
  • 33
  • 60
1
const result: Boolean = strValue === "true" ? true : false
Manny
  • 134
  • 2
  • 15
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'));
Community
  • 1
  • 1
Justin Liu
  • 581
  • 6
  • 21
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'))
dippas
  • 58,591
  • 15
  • 114
  • 126
Neil Higgins
  • 51
  • 1
  • 8
  • It should be noted that using `eval` for trivial cases like this is NOT RECOMMENDED. Read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval – kabirbaidhya Sep 21 '20 at 16:04
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
Bhupender Keswani
  • 1,218
  • 1
  • 9
  • 16
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);
derekbaker783
  • 8,109
  • 4
  • 36
  • 50
Debasish Jena
  • 311
  • 2
  • 10
1

ES6+

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

const test = (val) => (val === "true" || val === "True")
console.log(test(string))
console.log(test(string2))
ru4ert
  • 998
  • 2
  • 14
  • 25
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;
}
Pablo Papalardo
  • 1,224
  • 11
  • 9
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);
    }
}
Vitim.us
  • 20,746
  • 15
  • 92
  • 109
0

The following would be enough

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

"true".boolean() // returns true "false".boolean() // returns false
cypher
  • 429
  • 1
  • 4
  • 16
  • 13
    Modifying the prototype is very bad idea – Szymon Wygnański Aug 07 '11 at 09:18
  • @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. http://webcache.googleusercontent.com/search?q=cache:whgHc3cedK0J:perfectionkills.com/extending-built-in-native-objects-evil-or-not/+&cd=1&hl=en&ct=clnk – cypher Dec 18 '12 at 09:19
  • 1
    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...). – Szymon Wygnański Jan 03 '13 at 20:40
0

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"`
guest271314
  • 1
  • 15
  • 104
  • 177
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
danday74
  • 52,471
  • 49
  • 232
  • 283
  • 2
    So it would return true for "False", would it not? – Oskar Berggren Nov 01 '17 at 18:07
  • @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`. – Justin Liu May 31 '20 at 16:05
  • @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`. – Oskar Berggren Jun 01 '20 at 20:06
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
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

To Kra
  • 3,344
  • 3
  • 38
  • 45
-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
Kal
  • 1,656
  • 4
  • 26
  • 41
-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.

M. Sherbeeny
  • 109
  • 2
  • 12
-1

var isTrueSet = eval(myValue);

Leo Muller
  • 1,421
  • 1
  • 12
  • 20
-3

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

Boolean(<stringVariable>)
Abderrahmen
  • 440
  • 3
  • 6
-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);
}
K-G
  • 2,799
  • 4
  • 26
  • 42
  • my bad i have fixed the above snippet - works now. not sure how those inverted commas "" got in there! ;/ @HugoZapata – K-G May 12 '15 at 14:07
  • But the question is, how to convert a string to boolean. new Boolean("false") doesn't work, so your answer is not correct. – Hugo Zapata May 12 '15 at 20:08
  • @HugoZapata updated the answer, yes was incorrect (but strangely was working before) updated answer works correctly now. – K-G May 15 '15 at 11:18
  • What is the point of the if/else? You are alert'ing the same thing in both branches. – foxdonut Jun 25 '15 at 19:34
  • @foxdonut 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. – K-G Jul 02 '15 at 14:57
-5

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

    const checkBoolean = Boolean("false"); 
    const checkBoolean1 = !!"false";  
    
    console.log({checkBoolean, checkBoolean1});  
Force Bolt
  • 1,117
  • 9
  • 9
-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.

Kev
  • 561
  • 5
  • 8
-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.