By Kevin


2008-11-05 00:13:08 8 Comments

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?

30 comments

@Bhupender Keswani 2020-08-12 09:08:51

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

@Neil Higgins 2020-07-22 19:49:27

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

@kabirbaidhya 2020-09-21 16:04:35

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/…

@ritesh 2020-06-03 14:36:05

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 2020-07-03 16:23:21

There are so many more performant and safer ways to do this.

@kabirbaidhya 2020-09-21 16:06:41

This isn't a recommended solution. Read more - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@Mohammad Farahani 2017-07-25 04:53:14

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

@D. Pardal 2020-07-03 16:26:11

Not guaranteed to return a boolean, though.

@Justin Liu 2020-05-31 15:26:53

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'));

@jacobq 2020-05-08 14:51:31

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

@Mansi 2020-05-08 08:01:42

const result: Boolean = strValue === "true" ? true : false

@Faizan Khan 2020-02-27 10:06:40

The most simple way is

a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;

@Patrick Matte 2020-05-01 18:59:02

Here's mine function boolify(value = false) { return ["true", "1", "yes", "y", "on"].indexOf(String(value).toLowerCase()) != -1; }

@panatoni 2019-05-31 09:23:31

The simplest way which I always use:

let value = 'true';
let output = value === 'true';

@zeross 2019-06-06 08:05:50

Ternary operator is not necesary. Only with let output = value === 'true' works.

@panatoni 2019-06-07 12:59:29

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?

@zeross 2019-06-07 13:35:21

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.

@panatoni 2019-08-16 21:03:16

Yeah sure you are right, I edited my answered - my fault ;]

@sçuçu 2020-02-20 16:48:03

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

@James Anderson Jr. 2020-01-20 14:05:53

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

@Luke 2011-10-20 09:35:03

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());

@BishopZ 2013-01-26 22:52:12

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.

@Luke 2013-02-06 23:19:02

Great point BishopZ. I upvoted your solution using a regular expression: /^true$/i.test( myValue )

@jedmao 2013-05-15 01:00:09

@Luke this solution is actually exactly what I needed; well, wrapping it in a try...catch though. I wanted to convert to bool only if it was a boolean value in the string; otherwise, just use the string provided. This works! Thanks.

@toniedzwiedz 2013-07-10 17:07:45

When I have to parse a string and create a boolean, it's usually taken from markup, mostly attributes. For such use case, JQuery's data function can be used. var someBool = $('elementselector').data('attributeselector') === true; This doesn't throw an exception.

@Yuck 2013-08-08 15:00:49

It's pretty simple to just say JSON.parse("TRUE".toLowerCase()) so that it can parse correctly.

@Ebenezar John Paul 2014-07-08 06:12:02

It doesn't work with ie7 unless you include JSON library externally.

@sospedra 2015-02-18 16:17:26

Here stackoverflow.com/a/28588344/2824333 there are the performance comparison.

@fuelusumar 2015-05-19 21:40:22

this way it always parse false as value

@TheAnimatrix 2016-10-12 07:32:55

Dont give up at the point that no one uses ie , this maybe irrelevant here but you guys maybe making your code vulnerable when accessed from browsers like ie , say the error it produces could potentially crash your program/server

@Maksim Vi. 2016-11-19 10:12:54

why there are so many upvotes? This is inefficient and horrible.What's next? 'true'.length === 4?

@Vitim.us 2017-05-08 15:27:46

@MaksimVi. typeof str==="string" && str.length===4 && str.charAt(0)==="t" && str.charAt(1)==="r" && str.charAt(2)==="u" && str.charAt(3)==="e" && true===true && true!==false && false===false //just to be sure

@Danielo 2020-06-03 11:03:26

consider also a regexp at this point new RegExp('true','i').test('TrUe')

@olegtaranenko 2019-10-20 06:16:59

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

@Al Albers 2019-04-08 09:20:18

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.

@Yuriy Litvin 2019-03-06 09:16:09

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

@Ratan Uday Kumar 2019-01-08 10:16:22

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

@Metonymy 2019-02-25 15:50:04

I'd rather not introduce a new dependency to the project just for converting a string to a boolean.

@Ratan Uday Kumar 2019-02-26 03:32:27

It is very light weight and also u can validate whether string is boolean

@pankaj sharma 2018-02-22 14:26:25

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

@guinaps 2008-11-05 00:51:02

Do:

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

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==).

var isTrueSet = (myValue === '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.

@Tim Down 2010-08-26 11:01:45

myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here.

@guinaps 2011-02-10 15:37:40

I follow Crockford's advice and use === and !== whenever it makes sense, which is almost always.

@BMiner 2011-08-10 22:45:33

What about "TRUE" in all uppercase, for example?

@Muhd 2011-12-23 20:20:14

@BMiner then convert myValue to lowercase first.

@cciotti 2012-02-21 22:07:07

@guinaps When does it make the most sense?

@Aidiakapi 2012-04-26 15:10:01

@cciotti When you don't want implicit type coercion. OR like guinaps said, almost always.

@manalang 2012-09-26 21:24:24

Hmmm... what about: /^true$/i.test("false");

@epidemian 2012-09-28 19:17:15

@TimDown That's true if myValue is a string, if it's for example an array ['true'] or even an array of arrays [['true']] then myValue == 'true' will also verify, which is probably undesirable :)

@Tim Down 2012-09-28 20:31:38

@epidemian: Yes. However, myValue comes from the value property of a form input, so is guaranteed to be a string. I concede that I could have made that point explicit in my original comment.

@JMTyler 2013-05-09 18:11:45

@guinaps I usually follow Crockford's advice, but the == vs. === scenario is one of the few in which I do not. I completely disagree that it "almost always" makes sense to use ===. Loosely-typed languages exist because we don't want to care about the type; if we check something like if (price >= 50) we don't care if it began as a string. I say, most of the time, we want types to be juggled. In the rare cases where we don't want type juggling (e.g. if (price === null)), then we use ===. This is what I've done for years and I've never had an issue.

@JMTyler 2013-05-09 18:16:24

@guinaps And yes, I know that to be incredibly proper, I should actually compare with parseInt(price, 10), not simply price... but I ask that if you respond, you are sensible and attack my underlying concept, but not my off-hand examples.

@user123444555621 2013-06-23 06:06:30

@JMTyler I completely agree. In my whole career I actually run into an issue only once, when I didn't use if (foo !== 0), but if (foo). Wait.... Crockford doesn't advise against that...

@aikeru 2013-07-02 17:36:06

@JMTyler might be overlooking the maintenance programmer coming after. Always use the proper comparison operator! If you know 'for sure' the types on both sides, but don't use ===, I wont have that knowledge when looking at your code later. If your code is reused this can become a nightmare. If you REALLY want your types 'juggled' as you say, then use '==', but too many JS devs will trip on this too easily, better to tighten up your code. How often do I want string 'false' to signify boolean 'true'?

@Michael Bushe 2014-03-27 22:58:36

To cover upper case: !!(''+myValue).toLowerCase(); or ((''+myValue).toLowerCase() === 'true');

@Daniel Sokolowski 2014-06-24 02:03:53

I find Crockford to be over quoted and some of his JS conventions just bad. Example variable declaration at the top and being comma separated is error prone and not practical; I say declare for code readability and always use var keyword for explicitly.

@Hejazzman 2014-09-04 00:10:42

I agree re: variable declaration at the top. For one, having the declaration just before the actual use makes you think about the "logical" scope you want that variable in (regardless if its available throught a closure or not). Second, in the future (ES6) you can just replace those "var" with "let" and you'll have that logical scope enforced too.

@joeytwiddle 2014-09-23 07:08:16

To support @aikeru's point, this might end painfully if you let price be a String (or if you just aren't sure): if (price >= 50) { price += 10; }

@Tomas 2014-10-17 12:22:04

Boolean("false"); gives me true!

@jkutianski 2014-11-01 09:51:48

I think the best way is var isTrueSet = myValue.match(/true/i) && true || false;

@fuelusumar 2015-05-19 21:41:58

just did var isPriv = is_priv.toLowerCase() == 'true'; and worked

@Cezary Daniel Nowak 2015-06-15 15:58:12

@TimDown You're not right. Try: var myValue = {toString:function(){return "true"}};

@Tim Down 2015-06-15 21:25:06

@CezaryDanielNowak: Yes. However, in the context of the question, myValue comes from the value property of a form input so is guaranteed to be a string. Ah, it turns out I had this exact exchange with someone else earlier in the comments. Unfortunately I can't now change my first comment to be more explicit about this.

@Hugo Zink 2015-10-07 10:51:38

@guinaps that source also says your lines should be no longer than 80 characters, even though we have not used punch cards in many decades. It's a pointless and arbitrary standard. Besides, loose comparison is often enough. Javascript is weakly typed for a reason.

@sospedra 2015-11-02 10:56:59

But, for example: string = "beep" will parse to false which isn't expected. Maybe swtich/case is a better approach, hu?

@DavidS 2015-12-03 18:52:57

Yes, @HugoZink, Javascript is weakly typed for a reason, and this isn't it. "Weakly typed" does not mean "performs random, counterintuitive conversions", and anyone explaining the benefits of weak typing and Javascript would be doing both a discredit to use this behaviour as a good example.

@TheCuBeMan 2016-01-12 10:20:44

'TRUE' is not 'true' because there is a meaning for upper/lower-case characters in JavaScript. Therefore, these two strings are different by nature and the "===" (or even "==", for that matter), will return false.

@Pawel 2016-10-13 15:08:56

@TimDown The benefit of using === here is to forget about == forever and avoid being tempted to use it anywhere else.

@Pawel 2016-10-14 08:45:46

@TimDown and any other serious developer. When you choose to use == the code becomes inconsistent and every linter will complain.

@Tim Down 2016-10-14 09:55:06

@Pawel: I disagree that not using == is the only possible choice for a serious developer. It's a useful code standard in a team of mixed experience or ability but in a context where everyone dealing with the code understands the language then I don't see a problem. Appeasing a linter isn't a good reason on its own to adopt a particular standard, and most linters can be configured anyway.

@Pablo S G Pacheco 2017-01-26 13:27:13

The problem here is it doesn't work with 0 nor 1. So it can't be good.

@Andrew Luca 2017-02-22 03:59:09

!!(parseInt(value) || value === "true")

@Peter Raeves 2017-02-27 09:24:43

What if 'True' comes in. When I check 'value == 'true'' it returns false...

@MyiEye 2017-06-19 14:13:08

Perhaps the strangest thing here is that the boolean value true results in false. If you convert the value explicitly to a string first, that won't happen.

@El Mac 2018-04-13 09:26:12

@Geoffrey Hale why was this answer edited like that? The original answer was at least as correct. Why did you choose to mark it as "unnecessary", even if it is correct? Why do you think you can decide what's better?

@Geoffrey Hale 2018-04-25 01:11:34

@ElMac I don't know what's not obvious about my edit, nor who or how you are relevant to this question/answer thread. I improved the organization of the post with headings related to the original posters question and the behavior of '==' and '===' operators; the approver of my edit agrees. Private message me if you are still confused, thanks.

@Francesco Jo 2018-09-20 13:35:27

const str = new String("true");, console.log(str == "true"); // will be true, console.log(str === "true"); // will be false Be careful using === when to test whether the string literal can be parsed as boolean. I wasted 2 hrs because of this feature of Javascript. BTW I wanna indent the code above but Stackoverflow does not allow me. It's really frustrating.

@Black Mamba 2018-11-13 06:38:51

I just did this and watched it fail false == 'false' which should've been true but returns a false

@Zarathuztra 2019-10-30 00:07:52

@FrancescoJo you can't indent code in SO comments. that would be a nightmare to read through. There's a reason it's limited to like 512 characters... moving on, though, I see a huge problem with any time a string is used for a boolean. you must always be sure to check BOTH "true" and "false". If you only check for "false" everything else is true. if you only check for "true", everything else is false, even truthy values like 1. If your system is throwing around booleans as strings, I'd fix that problem as soon as possible, not bandaid it. Just my two cents, and I know this is old

@2540625 2020-01-18 02:11:18

Parentheses are unnecessary here.

@Ketan Patil 2020-01-29 09:29:22

This is so counter-intuitive.

@BotanMan 2020-02-07 22:32:14

one option to do that is use JSON.parse("true") === true and JSON.parse("false") === false, while it could raise an exception, so be careful

@Justin Liu 2020-06-07 21:08:47

You could wrap it in a try{} block so it wouldn't throw an exeption without a catch(e){}

@Shadow2531 2008-11-05 02:15:28

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)

@Shadow2531 2011-07-16 19:06:07

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.

@devios1 2011-09-12 14:29:24

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

@guzart 2012-02-04 20:52:01

To follow convention I would call it parseBool

@Thomas W 2012-08-14 22:40:26

Boolean parsing doesn't belong in the String class.. you would end up with any amount of rubbish parsers & conversion there. -1 to changing prototypes generally. -1 to solutions that don't work cross-browser. -1 for poor design.

@Joseph Lennox 2013-05-26 18:28:54

@chaiguy It's a lot more complex then "it exists, and this is a use, there for it's the correct use." There's no name spacing -- nothings stopping multiple libraries from having naming collisions. Relying on typing can become error prone -- var foo = ""; foo = getValue(); foo.someStringPrototype(); can result in an exception because getValue() may return null, undefined, or another non-string value.

@jordancpaul 2013-09-20 22:27:54

Using regex is slow. Using some straightforward loops and measuring with console.time/console.timeEnd, I found the regex solution to be about 50-75% slower than just testing equality against "true". Even if you use toLowerCase

@Serj Sagan 2015-02-05 21:35:28

None of these "don't modify the prototype" rules make any sense... they only say that because they were taught these things by their outdated college professors. Saying to not modify the prototype in JS is the same as saying don't write extension in C#...which is of course ridiculous. I can agree that it makes sense not to use this if this is some kind of project that can be downloaded and used by others...if you're using it in your own app or site then there is nothing with doing it this way... completely ruling out a method is the ignorant approach... do what makes sense in your context.

@sospedra 2015-02-18 16:17:55

Here's a performance comparison of all the answers. stackoverflow.com/a/28588344/2824333

@Chev 2015-06-24 18:36:56

Use this same method but on some custom utility funciton or something. Don't augment the string prototype, not even with defineProperty.

@Dan Pantry 2016-01-07 09:36:47

@SerjSagan it is not the same as an extension method in C# because you only get access to extension methods if you include the correct namespace. Modifying the prototype affects all instances of the thing you modified in that instance of the runtime. Additionally, punching the duck is bad form honestly is really confusing. how the hell am I to know where this weird method on a string is coming from, for one? It could be from anywhere in my code base..

@James Gentes 2020-08-14 16:48:02

I thought this was perfect: /^\s*(true|1|on)\s*$/.test()

@Hakan Fıstık 2016-11-25 08:57:12

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');

@Angelo Oparah 2020-06-14 09:46:11

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

@Yohan 2017-12-14 15:44:37

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

@OhkaBaka 2017-11-30 21:57:54

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;

@Kostanos 2017-10-26 01:34:44

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

@BrDaHa 2014-02-24 00:00:44

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

@philk 2014-06-30 12:10:09

I use this one as it covers things you get from XML/HTML ElementNodes attributes like autocomplete="on"

@Luis Lobo Borobia 2017-11-20 18:05:17

I would add .trim() before toLowerCase()

@danday74 2017-08-01 22:56:20

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

@Oskar Berggren 2017-11-01 18:07:18

So it would return true for "False", would it not?

@Justin Liu 2020-05-31 16:05:48

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

@Oskar Berggren 2020-06-01 20:06:44

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

@guest271314 2017-07-19 05:21:07

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

@Chanakya Vadla 2017-05-16 08:34:05

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.

@James Wilkins 2019-09-06 19:07:32

Or true.toString()==='true'. Also, why are you making String(true) and String('true') lowercase? lol

@Vitim.us 2017-05-08 15:52:58

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

@Dayem Siddiqui 2017-04-29 11:08:04

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

@serdar.sanri 2019-05-08 15:04:17

wouldn't return str.toLowerCase() === 'true' simpler?

@Dayem Siddiqui 2019-05-09 17:17:05

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'

@Surya R Praveen 2017-04-10 15:59:47

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*/);

Related Questions

Sponsored Content

95 Answered Questions

[SOLVED] How to validate an email address in JavaScript

46 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

70 Answered Questions

[SOLVED] How to replace all occurrences of a string?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 7126187 View
  • 8647 Score
  • 97 Answer
  • Tags:   javascript arrays

94 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

47 Answered Questions

[SOLVED] How can I check for an empty/undefined/null string in JavaScript?

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

3 Answered Questions

Sponsored Content