How can I convert a string to boolean in JavaScript?
Solution 1
Do:
var isTrueSet = (myValue === 'true');
using the identity operator (===
), which doesn't make any implicit type conversions when the compared variables have different types.
This will set isTrueSet
to a boolean true
if the string is "true" and boolean false
if it is string "false" or not set at all.
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
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
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
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
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.
Imad
Updated on July 08, 2022Comments
-
Imad almost 2 years
I know
WPF
. I want to start a smallWPF App
that will interact with database (SQL Server
). I know how to develop it locally but I am worried about deployment. Client machine don't have.Net
orSQL Server
. Client OS may beWindows XP
orWindows 7
. WhatORM
should I use? How to addDatabase
in my project?edmx
,service-based databse
?? or something other?-
yurisich over 10 yearsJust to highlight an odd example of avoiding triple-equals comparison: I have a function
currentSortDirection()
that returns1
for an ascending sort,0
for a descending sort, and-1
for not set. Usingwhile (currentSortDirection() != desiredSortDirection) { sortColumn() }
works great, since-1 != true
and-1 != false
...but changing this towhile (Boolean(currentSortDirection) !== ...) {...}
forces-1
into atrue
, necessitating an additional couple of lines of prep, just to make jshint happy. -
Rodrigo Siqueira over 10 yearsPossible duplicate of stackoverflow.com/questions/263965
-
Nope about 10 years@Droogans: What happens if
desiredSortDirection
is set toasc
? I know in a controlled environment you are probably in control over the valuedesiredSortDirection
is set to but in a shared environment when the input ofdesiredSortDirection
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. -
Mark K Cowan about 9 years"Is there a better way to accomplish this?" - there is certainly a worse way :D
string=(string==String(string?true:false))?(string?true:false):(!string?true:false);
-
Leastrio over 8 yearsEasily handle strings and bools:
function parseBool(val) { return val === true || val === "true" }
-
Ranadheer Reddy almost 8 yearsarticle with good explanation coding-issues.com/2015/11/…
-
Sebi over 7 years@Mark
function checkBool(x) { if(x) {return true;} else {return false;} }
-
Mark K Cowan over 7 years@Sebi: You forgot to document it:
if (checkBool(x) != false) { ... } else { ... }
-
iamandrewluca about 7 years
!!(parseInt(value) || value === "true")
-
vitaly-t over 4 yearsYou can't, it is impossible!
-
Agnius Vasiliauskas over 4 yearsJust a note. I am always amazed by Javascript expression parsing rule-set, for example,
123+44+'2'+1
gives"16721"
. Every + after '2' is interpreted as concatenation operation, wow :-D. While PHP gives 170 as an answer, which is more transparent, because in PHP plus is not ambiguous - it is just used for arithmetic operations. Concatenation operation is performed with different operator -
Milos Radojevic over 4 yearsI haven't found an answer which solves undefined+string combination properly. So eventually I wrote one-liner for this:
const StrToBool = (value) => !!value && value !== "false" && parseInt(value) !== 0;
This one liner gives following results:StrToBool(undefined) => false, StrToBool('true') => true, StrToBool('false') => false, StrToBool('0') => false, StrToBool('Whatever') => true, StrToBool('1') => true
-
Admin almost 4 yearsWhy would you want to?
-
Firzok Nadeem almost 4 yearsFor these types of conversions, a good solution is to use a site like converttypes.com where you can see all conversions for almost all programming languages.
-
ZenAtWork almost 4 years
!myVar.slice(4,5);
myVar = 'TRUE' // true
myVar = 'FALSE' // false
-
danbars over 3 years@AndrewLuca 's answer is great - it handles undefined, null and all other types. It considers non-zero numbers as true as well as the string 'true'. And all in a concise way.
-
varun sharma about 3 years
toBool ={'false':false,'true':true } invertBool = {'false':true,'true':false}
can be usedtoBool[string]
-
Deepak paramesh almost 3 yearsJSON.parse('true') is the most easiest way to convert to boolean
-
-
Thomas Eding over 14 years-1: Please don't advocate the use of eval (except perhaps for clever hacks and necessity).
-
moo over 14 yearsthat's a really bad and insecure use of eval. and it's not even clever. -1
-
Mariano Desanze almost 14 yearsWhy 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: stackoverflow.com/questions/359494/… -
Tim Down over 13 years
myValue === 'true';
is precisely equivalent tomyValue == 'true';
. There is no benefit in using===
over==
here. -
guinaps over 13 years
-
tillda about 13 yearsYou can use true.toString() instead of "true" to be even more clean :-)
-
Shadow2531 almost 13 yearsYou 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.
-
Szymon Wygnański almost 13 yearsModifying the prototype is very bad idea
-
devios1 over 12 years@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
. -
pauloya about 12 yearsWhen you can receive a string in uppercase or a boolean, then
String(a).toLowerCase() === 'true'
-
YMMD about 12 yearsWhat conversion were you talking about? :-)
-
GrahamMc over 11 yearsTo understand what's "wrong" (or right) with eval - check out articles like javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval or search on stackoverflow for 'Javascript eval malware'
-
cypher over 11 years@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/…
-
ars265 over 11 yearsWhen comparing string in javascript there is no difference between using the == or === operators when not using conversions. Here you are comparing to strings, therefore no type conversions. See stackoverflow.com/questions/359494/…
-
Szymon Wygnański over 11 yearsConsider: 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...).
-
BishopZ over 11 yearsThe 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.
-
thdoan over 11 yearsI agree that
var isTrueSet = (myValue === 'true');
is the best answer. -
JMTyler about 11 yearsJust to go back to your objectives, the only problem with your third & best solution is that it does not meet Objective #1 - it will only return true for a value of
'true'
, but not for any truthy input. In order to make it meet Objective #1, it is only slightly more concise than Solution #2, and far less readable. -
Robert almost 11 yearsActually it can be simplified. 1) There is no need to test for
"true"
,"yes"
and"1"
. 2)toLowerCase
does not returnnull
. 3)Boolean(string)
is the same asstring!==""
here. =>switch(string.toLowerCase()) {case "false": case "no": case "0": case "": return false; default: return true;}
-
Robert almost 11 yearsSince
value
will always be astring
neither==
nor===
are silly. Both are the right tool for this job. They only differ when the types are not equal. In that case===
simply returnsfalse
while==
executes an intricate type coercion algorithm before comparison. -
Yuck almost 11 yearsIt's pretty simple to just say
JSON.parse("TRUE".toLowerCase())
so that it can parse correctly. -
Etienne almost 10 yearsThe 'without JSON' version has some flaw: val="0" ; console.log(!!(+val||String(val).toLowerCase().replace(!!0,'')) ); produces true
-
Ron Martinez over 9 years
getBool(undefined)
will crash When using the original JSON version and will return true for the 2nd version. Here is a 3rd version which returns false: function getBool(val) { var num; return val != null && (!isNaN(num = +val) ? !!num : !!String(val).toLowerCase().replace(!!0,'')); } -
Imad over 9 yearsthanks for your reply. How can I bundle
.Net Framework Installer
andSQL Installer
? -
ViBi over 9 yearsIn case you are creating the installer using Installshield, you can add pre-requisites in it.
-
Imad over 9 yearsI dont want my client to install prerequisites seperately
-
jakubiszon over 9 yearsIf you wanted it short why not writing just
var isTrueSet = myValue === "true";
? -
whitfin over 9 years
JSON.parse
is able to handle parsing 'true' and 'false' to Boolean values, so you don't need to wrap it inBoolean()
. -
MarceloBarbosa over 9 yearsThis is good, but works only with String type. Imagine that this need be used by a variable that is maybe
"true"
ortrue
. If come the second one, this will not work. Is possible make adocument.prototype
to use this wherever we want it? -
cassi.lup about 9 yearsThis looks elegant. Great job! However, I noticed that overloading basic prototypes in large JS apps (that also need unit testing) might result in some unexpected behaviour (namely, when you want to iterate with "for" through an array that has the prototype overloaded, you'll get some properties that you wouldn't normally expect). You have been warned. ;)
-
Pierre-Adrien about 9 yearsFor a string, I personnally would have returned
true
for "true" like you did, butfalse
for "false" only, andundefined
otherwise. Sort of what you previously made with the integer case. -
null about 9 yearsmy bad i have fixed the above snippet - works now. not sure how those inverted commas "" got in there! ;/ @HugoZapata
-
Hugo Zapata about 9 yearsBut the question is, how to convert a string to boolean. new Boolean("false") doesn't work, so your answer is not correct.
-
null about 9 years@HugoZapata updated the answer, yes was incorrect (but strangely was working before) updated answer works correctly now.
-
foxdonut almost 9 yearsWhat is the point of the if/else? You are alert'ing the same thing in both branches.
-
null almost 9 years@foxdonut because if boolean == false, then you can do something different in the else statement - the alert is just an example. even though its the same it outputs something different if the boolean var = true/false.
-
Snowman almost 9 yearsI like that it's concise. But it fails spectacularly for the basic case of
eval('TRUE')
; proving once again, thateval()
is evil. -
thdoan almost 9 years@Area 51 Detective Fiction, in the same fashion,
JSON.parse('TRUE')
from the answer below also fails spectacularly. It's quite easy to force an error condition in JavaScript (or any language, for that matter). To account for this, you should normalize the string first, e.g.,var myValue = document.myForm.IS_TRUE.value.toLowerCase(); var isTrueSet = (myValue==='true' || myValue==='false') ? eval(myValue) : false;
-
Snowman almost 9 years@10basetom: Quite correct. You should include
.toLowerCase()
in the answer is my point. I'm not trying to force anything. UppercaseTRUE
is a common enough value to be returned by many UI widgets. -
bortunac over 8 yearsa variant of yours that accepts boolean too function StringOrElse2Bool(sob){ if (typeof sob === "string") { return ["no", "false", "0", "off"].indexOf( sob.toLowerCase() ) !== -1 ? false : true; } else { return !!sob }
-
Kevin Boucher almost 8 years
return /^(true|yes|1|t|y)$/i.test(str);
-
Oskar Berggren over 6 yearsSo it would return true for "False", would it not?
-
spottedmahn over 6 years"something went wrong" when trying to view jsPerf test
-
Steel Brain over 5 yearsDon't change globals, try to keep your changes isolated, maybe create a new
function parseBoolean
instead -
Zarepheth over 5 yearsAs written (on 2018 Dec 19 at 16:00 Z),
/^(false|0|no)*$/i
will match an empty string (which may be the intent) but also matches any numberfalse
,0
, orno
, for instance"0falseno0nofalse0"
will also evaluate tofalse
but should evaluate tonull
and output a console message that it is not a Boolean value. -
Denis Nutiu about 5 yearsI'd rather not introduce a new dependency to the project just for converting a string to a boolean.
-
Ratan Uday Kumar about 5 yearsIt is very light weight and also u can validate whether string is boolean
-
serdar.sanri about 5 yearswouldn't
return str.toLowerCase() === 'true'
simpler? -
Dayem Siddiqui about 5 yearsAh! 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'
-
zeross almost 5 yearsTernary operator is not necesary. Only with let output = value === 'true' works.
-
panatoni almost 5 yearslet 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 almost 5 yearsSorry, 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 almost 5 yearsYeah sure you are right, I edited my answered - my fault ;]
-
James Wilkins over 4 yearsOr
true.toString()==='true'
. Also, why are you makingString(true)
andString('true')
lowercase? lol -
thisismydesign about 4 years
Boolean("false")
=>true
-
Patrick Matte about 4 yearsHere's mine
function boolify(value = false) { return ["true", "1", "yes", "y", "on"].indexOf(String(value).toLowerCase()) != -1; }
-
Justin Liu almost 4 years@OskarBerggren It wouldn't. Look at the code,
if (bool === 'false') bool = false
then, when it runsreturn !!bool
it's returning!!false
which isfalse
. -
Oskar Berggren almost 4 years@JustinLiu jsfiddle certainly evaluates
toBoolean('False')
totrue
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 returntrue
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 astrue
. -
Angelo Oparah almost 4 yearsnot to mention that
.toLowerCase
might throw ifmyValue
is equal tonull
orundefined
-
D. Pardal almost 4 yearsThere are so many more performant and safer ways to do this.
-
D. Pardal almost 4 yearsNot guaranteed to return a boolean, though.
-
kabirbaidhya over 3 yearsIt 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/… -
kabirbaidhya over 3 yearsThis isn't a recommended solution. Read more - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
Vaibhav S over 3 yearsBoolean("false") === true // output true
-
Vaibhav S over 3 yearssimplified version: storeBooleanHere = stringVariable.toLowerCase() !== 'false' ;
-
Dan over 3 yearsFor such a simple task, a library would not be desirable especially when the library controls how a boolean is defined.
-
Shubham Chaudhary over 3 yearsQuoting mozzila docs:
Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval().
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…! -
Khanakia over 3 yearsWhat do we say this type of function ?
-
Wyck over 3 yearsDownvoted because you posted an image of the code rather than the code itself.
-
Jonathan Lyon over 3 yearsthis is so awesome and useful - thank you so much!
-
Prashanth Hegde about 3 yearsAny specific reason for using
!!v
instead of usingtrue
directly? -
jbalintac about 3 yearsIsn't
Boolean("false")
returnstrue
-
ksugiarto almost 3 yearsHow about
'1'
? Should it be converted totrue
orfalse
? I think it is should betrue
, no? But using your answer, it will returnsfalse
-
Felipe Chernicharo almost 3 yearsGuess you are doing something wrong bro... I just tested the code and if you input
' 1 '
the return is alwaystrue
. Don't know how you got thatfalse
but I think you must be messing it up in some way -
ksugiarto almost 3 yearsAh sorry! My bad, I was testing the first function instead. Thanks for clarifying this.
-
Akin Zeman almost 3 yearssame as y= (x=='true');
-
dav_i almost 3 yearsNote, this will default to
true
- for example:stringToBoolean('banana') // true
-
Alexander Santos almost 3 yearsThis sounds too specific. Mind explaining it?
-
Kieran Ryan almost 3 years@Wyck you failed to mention that presentation is nice.
-
Asinus Rex almost 3 yearsThis works, but you have to be careful not to pass it empty strings or it'll pop.
-
Richard Torcato over 2 yearsBoolean.prototype is fully supported in all browsers
-
earizon over 2 years@BishopZ : Stopping JS execution is probably a desirable feature following best-pattern coding styles: en.wikipedia.org/wiki/Fail-fast
-
earizon over 2 yearsif(str == null) return false; will return random errors each time an input is wrongly initialized to null. Being tolerant is not a desirable feature most of the times:
-
Muhammed Moussa over 2 yearsthe sexy solution, I liked it!
-
Woozar over 2 yearsThis will fail if myValue is null or undefined or any type other than a string.
-
June over 2 years@guinaps most of the javascript strict conventions to blanket apply to all javascript usage just cause convoluted code and a lack of understanding of the principles, theory, or usage of javascript.
-
NoxFly over 2 years
===
should be used because it's also checking for the right type. Also, it has better comparison performances than==
. -
prabhatojha over 2 yearshmm, this is perfect
-
opticyclic over 2 yearsPass "True" to this and it returns false
-
ru4ert over 2 years@opticyclic ok, i minded this and created a fix.
-
stu0292 over 2 yearsI'm using this approach for a framework that parses URL parameters and includes parameters without values as an empty string, something like:
example.com?useSpecialFeature
ends up as{useSpecialFeature:''}
-
Max Waterman over 2 yearsThis doesn't account for 'false'...if the string isn't 'true' or 'false', then myBool should probably be undefined. eg let myBool = (myValue === 'true')?true:(myValue === 'false')?false:undefined;
-
royce3 over 2 yearsyours was almost what I was looking for. Here's my variation: ``` function parseBool( value, nullOnFailure = false ) { let value2 = parseFloat( value ) if( !isNaN( value2 )) return !!value2 if( typeof value !== 'string' ) return !!value switch( value.trim().toLowerCase() ) { case 't': case 'true': case 'on': case 'y': case 'yes': return true case 'f': case 'false': case 'off': case 'n': case 'no': return false default: return nullOnFailure ? null : false } } ```
-
hargobind about 2 yearsI love the simplicity of the regex approach to check for values that are typically "true". A suggestion for modification: the logic of false is
0
and true is non-zero. Therefore I think it's better to check for the opposite of false, i.e.return !(/^(false|0|off|no)$/i).test(this);
-- also notice that I included "no". -
Just a coder about 2 yearstake all my money! 💵
-
Iglesias Leonardo about 2 yearsI would instead use
true
as1
andfalse
as0
. It would allow you to use methods likeparseInt()
and compare it's value usingif(parseInt(booleanVariable))
-
Jose Quijada about 2 yearsThanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans.
-
marko-36 about 2 yearsThis is a quick and dirty solution for storing true/false inside .env
-
Ivan Yulin about 2 yearsshould wrap in try/catch in many cases
-
Eve about 2 yearsIf we go by question title alone it goes out of discussion all that JSON thing. The question was about a string not about what can result from its transformation. Of course looking at an object "stored" in a string using the JSON format one can ask what happens in such a scenario. Or we could go as well another way towards strings converted in numbers (not into objects) for example
let x = 0 + "-0" // "0-0"
versuslet x = 0 - "-0" // 0
but, again, we move out of main topic :) -
Elijah Lynn almost 2 yearsThis does account for
false
as if the string doesn't match or is undefined then the conditional will evaluate to booleanfalse
. I updated the answer.