Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
    
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. – Droogans Nov 10 '13 at 17:56
    
Possible duplicate of stackoverflow.com/questions/263965 – Rodrigo Assis 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. – François Wahl Apr 24 '14 at 16:19
2  
"Is there a better way to accomplish this?" - there is certainly a worse way :D string=(string==String(string?true:false))?(string?true:fals‌​e):(!string?true:fa‌‌​​lse); – Mark K Cowan Apr 16 '15 at 10:25
2  
Easily handle strings and bools: function parseBool(val) { return val === true || val === "true" } – WickyNilliams Sep 10 '15 at 14:24

57 Answers 57

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/

share|improve this answer
1  
what about "1" and "0"... – pieterjandesmedt Apr 22 at 11:55
    
@pieterjandesmedt Thanks for the hint, fixed – Timo Apr 23 at 13:33
if (String(a) == "true"){
  //true block
} else {
  //false block
}
share|improve this answer

@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
share|improve this answer

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);
};
share|improve this answer

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 );
share|improve this answer

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');
        }
    }
};
share|improve this answer

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

share|improve this answer
3  
If you wanted it short why not writing just var isTrueSet = myValue === "true"; ? – Jakub Dec 18 '14 at 14:59
function isTrue(val) {
    try {
        return !!JSON.parse(val);
    } catch (e) {
        return false;
    }
}
share|improve this answer

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';  
share|improve this answer

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.

share|improve this answer
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);
    }
}
share|improve this answer

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.

share|improve this answer

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;
share|improve this answer

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; }
    }
  }
share|improve this answer

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

share|improve this answer
    MyLib.Convert.bool = function(param) {
         var res = String(param).toLowerCase();
         return !(!Boolean(res) || res === "false" || res === "0");
     }; 
share|improve this answer

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
share|improve this answer

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.

share|improve this answer

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;
  };
}
share|improve this answer

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'
share|improve this answer

The following would be enough

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

"true".boolean() // returns true "false".boolean() // returns false
share|improve this answer
10  
Modifying the prototype is very bad idea – Szymon Wygnański Aug 7 '11 at 9: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. webcache.googleusercontent.com/… – cypher Dec 18 '12 at 9: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 3 '13 at 20:40

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.

share|improve this answer
Boolean(Number(value));
var value = 1;  //true
var value = "1" //true
var value = 0;  //false
var value = "0" //false`
share|improve this answer

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

share|improve this answer
1  
Doesn't work for "false" – Hugo Zapata Apr 28 '15 at 16:07
    
my bad i have fixed the above snippet - works now. not sure how those inverted commas "" got in there! ;/ @HugoZapata – whitedeath 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. – whitedeath 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
If(value === 'true') 
    return true
return false
share|improve this answer
    
It definitely working to me. I don't know why two down votes – Parthipan S May 22 at 9:20
    
Possibly because it's a question with 55 other answers, and your answer doesn't add anything which isn't covered by the other answers. – DavidW May 22 at 10:23
 var myBool = Boolean.parse("true");

or

var myBool = Boolean("true");

or

var myBool = !!"true";

Not sure if the first one is IE specific.

share|improve this answer
8  
Here is the thing with using Boolean("true"). It is a little misleading because Boolean("false") and Boolean('wtf") evaluate to true as well. Your third answer is very similar to mine. – Kevin Nov 5 '08 at 0:27
    
@FlySwat: I know it's an old answer but it still shows up in the top search results so other users will see it. The third example which uses !! is also unreliable. !!"true"; will return true but so will !!"false"; and !!"abc";. When JavaScript processes a string with 'true' or 'false' it does not distinguish between those values. It simply sees them both as strings with a value. Therefore using the ! operator on a string: !'anyValue' and even !' ' will always be false and only !'' will be true. – François Wahl Apr 24 '14 at 15:35

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.

share|improve this answer
10  
-1: Please don't advocate the use of eval (except perhaps for clever hacks and necessity). – Thomas Eding Jan 22 '10 at 0:32
    
that's a really bad and insecure use of eval. and it's not even clever. -1 – moo Jan 22 '10 at 0:35

protected by Tushar Gupta Apr 28 '14 at 12:56

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.