How can I convert a string to boolean in JavaScript?
JavascriptBoolean ExpressionBoolean OperationsString ConversionJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
Do:
var isTrueSet = (myValue === 'true');
using the identity operator (===
), which doesn't make any implicit type conversions when the compared variables have different types.
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.
Solution 2 - Javascript
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());
Solution 3 - Javascript
stringToBoolean: function(string){
switch(string.toLowerCase().trim()){
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
return false;
default:
return Boolean(string);
}
}
Solution 4 - Javascript
I think this is much 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
Solution 5 - Javascript
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.
Solution 6 - Javascript
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)
Solution 7 - Javascript
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);
Solution 8 - Javascript
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)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if(str == null)
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]));}
Solution 9 - Javascript
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
Solution 10 - Javascript
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/
Solution 11 - Javascript
Your solution is fine.
Using ===
would just be silly in this case, as the field's value
will always be a String
.
Solution 12 - Javascript
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());
Solution 13 - Javascript
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 implications when using eval()
though.
Solution 14 - Javascript
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):
- Conditional statement: 2,826,922
- Switch case on Bool object: 2,825,469
- Casting to JSON: 1,867,774
- !! conversions: 805,322
- 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.
Solution 15 - Javascript
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');
Solution 16 - Javascript
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".
Solution 17 - Javascript
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.");
}
};
Solution 18 - Javascript
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
Solution 19 - Javascript
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
Solution 20 - Javascript
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
Solution 21 - Javascript
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"
Solution 22 - Javascript
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
Solution 23 - Javascript
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)));
Solution 24 - Javascript
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"
Solution 25 - Javascript
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
Solution 26 - Javascript
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
Solution 27 - Javascript
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. :-)
Solution 28 - Javascript
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
, ''
).
Solution 29 - Javascript
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!
Solution 30 - Javascript
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;
}
}
Solution 31 - Javascript
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..
Solution 32 - Javascript
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
>
Solution 33 - Javascript
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;
Solution 34 - Javascript
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!
Solution 35 - Javascript
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;
};
Solution 36 - Javascript
The simplest way which I always use:
let value = 'true';
let output = value === 'true';
Solution 37 - Javascript
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;
}
Solution 38 - Javascript
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';
Solution 39 - Javascript
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.
Solution 40 - Javascript
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.
Solution 41 - Javascript
The most simple way is
a = 'True';
a = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;
Solution 42 - Javascript
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?
Solution 43 - Javascript
@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
Solution 44 - Javascript
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.)
Solution 45 - Javascript
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/
Solution 46 - Javascript
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
Solution 47 - Javascript
/// 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
Solution 48 - Javascript
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.
Solution 49 - Javascript
if (String(a) == "true"){
//true block
} else {
//false block
}
Solution 50 - Javascript
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);
};
Solution 51 - Javascript
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 );
Solution 52 - Javascript
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
Solution 53 - Javascript
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;
};
}
Solution 54 - Javascript
function isTrue(val) {
try {
return !!JSON.parse(val);
} catch (e) {
return false;
}
}
Solution 55 - Javascript
I use this simple approach (using "myVarToTest"):
var trueValuesRange = ['1', 1, 'true', true];
myVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);
Solution 56 - Javascript
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
Solution 57 - Javascript
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
Solution 58 - Javascript
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
Solution 59 - Javascript
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;
}
Solution 60 - Javascript
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;
};
};
Solution 61 - Javascript
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);
});
}
}
});
Solution 62 - Javascript
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")
Solution 63 - Javascript
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();
Solution 64 - Javascript
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;
Solution 65 - Javascript
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; }
}
}
Solution 66 - Javascript
MyLib.Convert.bool = function(param) {
var res = String(param).toLowerCase();
return !(!Boolean(res) || res === "false" || res === "0");
};
Solution 67 - Javascript
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');
}
}
};
Solution 68 - Javascript
A shorter way to write this, could be var isTrueSet = (myValue === "true") ? true : false;
Presuming only "true" is true and other values are false.
Solution 69 - Javascript
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.
Solution 70 - Javascript
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'
Solution 71 - Javascript
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'))
Solution 72 - Javascript
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.
Solution 73 - Javascript
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);
}
}
Solution 74 - Javascript
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.
Solution 75 - Javascript
You even do not need to convert the string to boolean. just use the following:
var yourstring = yourstringValue == 1 ? true : false;
Solution 76 - Javascript
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
.
Solution 77 - Javascript
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.
Solution 78 - Javascript
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*/);
Solution 79 - Javascript
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;
}
Solution 80 - Javascript
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);
Solution 81 - Javascript
const result: Boolean = strValue === "true" ? true : false
Solution 82 - Javascript
if
statment:
Use an 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'));
Solution 83 - Javascript
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'))
Solution 84 - Javascript
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
Solution 85 - Javascript
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
Solution 86 - Javascript
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);
Solution 87 - Javascript
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;
}
}
Solution 88 - Javascript
ES6+
const string = "false"
const string2 = "true"
const test = (val) => (val === "true" || val === "True")
console.log(test(string))
console.log(test(string2))
Solution 89 - Javascript
The following would be enough
String.prototype.boolean = function() {
return "true" == this;
};
"true".boolean() // returns true "false".boolean() // returns false
Solution 90 - Javascript
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"`
Solution 91 - Javascript
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
Solution 92 - Javascript
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
Solution 93 - Javascript
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.
Solution 94 - Javascript
The simplest way to convert a string to a boolean is the following:
Boolean(<stringVariable>)
Solution 95 - Javascript
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);
}
Solution 96 - Javascript
// Try this in two ways convert a string to boolean
const checkBoolean = Boolean("false");
const checkBoolean1 = !!"false";
console.log({checkBoolean, checkBoolean1});
Solution 97 - Javascript
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.
Solution 98 - Javascript
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.