tags:

views:

26914

answers:

13

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?

A: 
 var myBool = Boolean.parse("true");

or

var myBool = Boolean("true");

or

var myBool = !!"true";

Not sure if the first one is IE specific.

FlySwat
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
+48  A: 

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.

About the way you suggested, 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 (==), which does:

var isTrueSet = (myValue === 'true');
guinaps
`myValue === 'true';` is precisely equivalent to `myValue == 'true';`. There is no benefit in using `===` over `==` here.
Tim Down
+5  A: 

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
why would you do a ternary? you already have a boolean there
nickf
Because you can? What do you mean by "you already have a boolean there"?
Jared Farrish
Doh! toLowerCase. Doh!
Jared Farrish
Jared, the === already is a boolean condition, the ternary is redundant.
FlySwat
True. I hate ternaries anyways. Well, I think I'm right on the toLowerCase, so I edited it to remove the ternary.
Jared Farrish
+4  A: 

Your solution is fine.

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

insin
This is the only sensible answer here :)
Bobby Jack
@insin, 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
Protron
A: 

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
A: 

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
+14  A: 
String.prototype.bool = function() {
    return (/^true$/i).test(this);
};
alert("true".bool());
Shadow2531
+1  A: 

I think this is much universal: if (String(a) == "true") ...

It goes:

String(true) == "true" //returns true

String(false) == "true" //returns false

String("true") == "true" //returns true

String("false") == "true" //returns false

A: 

if (String(a) == "true"){ //true block } else{ //false block }

+7  A: 
stringToBoolean: function(string){
 switch(string.toLowerCase()){
  case "true": case "yes": case "1": return true;
  case "false": case "no": case "0": case null: return false;
  default: return Boolean(string);
 }
}
A: 

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.

PixelSlave
-1: Please don't advocate the use of eval (except perhaps for clever hacks and necessity).
trinithis
that's a really bad and insecure use of eval. and it's not even clever. -1
orlandu63
+4  A: 
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.");
  }
};
trinithis
A: 

The following would be enough

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

"true".boolean() // returns true "false".boolean() // returns false
cypher