Reputation: 7946
Can I convert a string representing a boolean value (e.g., 'true', 'false') into an intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based on 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?
Upvotes: 3593
Views: 3562946
Reputation: 3481
Using Node.js REPL
> t = 'true'
'true'
> JSON.parse(t)
true
> typeof JSON.parse(t)
'boolean'
>
Upvotes: 1
Reputation: 4041
var isTrueSet = (myValue === 'true');
Use the strict equality 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.
For making it case-insensitive, try:
var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');
You should be cautious about using these two methods for your specific needs.
var myBool = Boolean("false"); // evaluates to true
var myBool = !!"false"; // evaluates to 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.
Upvotes: 5049
Reputation: 17432
I think a good toBool
function would only test for true
values, and then typecast anything else into false
values. Unless there is a need, I would not include values like 'yep'
, 'yes'
, 'y'
, etc... because this list could be quite endless, and one does not normally see those as boolean true in other programming languages. However, it is common enough that four true values 'true'
, true
, '1'
, 1
could occur, and therefore should be supported.
This function has higher performance (337M ops/s ± 0.24%)
const toBool = value =>
(typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) ||
(typeof value === 'number' && value === 1) ||
(typeof value === 'boolean' && value === true)
;
This function has lower performance (44M ops/s ± 0.29%),
but is more customizable
(easier to add a value like 'yep'
if desired)
const toBool = value =>
['true', true, '1', 1].includes(typeof value === 'string' ?? value.toLowerCase());
Upvotes: 2
Reputation: 21
let str = "true";
let boolValue = (str === "true");
console.log(boolValue); // true
`
Upvotes: 1
Reputation: 1
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.");
}
};
Upvotes: 14
Reputation: 317
const booleanOfsomeVal = someVal == "1" || someVal == "true";
This should work in typescript & javascript both
considering someVal could have possible values
0/1/"0"/"1"/true/false/"true"/"false"/undefined/null/NaN
Upvotes: 0
Reputation: 12170
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' regardless
// of capitalization and regardless of 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)
Upvotes: 140
Reputation: 390
If you have no shame:
String.prototype.toTruth = function () {
const value = this.valueOf();
return value === 'true' ? true : value === 'false' ? false : undefined;
};
'true'.toTruth() // true
'false'.toTruth() // false
'falsest'.toTruth() // undefined
''.toTruth() // undefined
(Disclaimer: For the love of ECMA, don't do this.)
It's an interesting question, though, with more repercussions than one might expect.
I called it toTruth
and not toBoolean
because its return value can't always be a Boolean. One could argue that ''
should return false
, but what about other strings? Is it true
or false
?
Unless you use strict typing everywhere, with a 'true' | 'false'
union, there's no guarantee that your string is going to contain either true
or false
(or nothing). So logically, you have to allow for a third value, undefined
. (Or throw an error? No thanks.)
This means it actually becomes ternary logic, where undefined
is similar to SQL's NULL
(neither true
nor false
). That makes it much more complicated than a simple true
/false
predicate. Especially when you add JavaScript's truthiness to the equation, where an undefined
value might be evaluated as false
(falsy).
If you have no shame and actually want to use this (dear god), you should explicitly check against the value you want with ===
and not use negation (unless you know what you're doing, keep in mind that it's ternary logic):
const input = 'foo'; // or anything else but 'true' or 'false'
input.toTruth() // undefined
!input.toTruth() // true (misleading, it's not false)
input.toTruth() !== true // true (misleading, it's not false)
input.toTruth() === false // false (correct)
input.toTruth() === true // false (correct)
input.toTruth() === undefined // true (correct)
I like JavaScript and I like ternary logic. But carelessly combining the two is a recipe for disaster.
A statically typed language like TypeScript does make it a lot easier. However, the same caveats apply when your code is exposed to code or input you don't control.
type BooleanString = 'true' | 'false'
function toBoolean(predicate: BooleanString): boolean {
return predicate === 'true';
}
function toTruth(predicate: string): boolean | undefined {
return predicate === 'true' ? true : predicate === 'false' ? false : undefined;
}
Upvotes: 1
Reputation: 139
The easiest way of doing this, especially if you're getting the 'true' or 'false' from an input type of radio ie
<input type='radio' name='IsAllowedToWork' value={true} onChange{handleChange} />
<input type='radio' name='IsAllowedToWork' value={false} onChange{handleChange} />
is this
const handleChange = (e) => {
let { value ,type} = e.target;
if (type==='radio') {
value = JSON.parse(value);
} else if (type === 'file') {
value = e.target.files[0];
}
setValues({ ...values, [e.target.name]: value });
};
Upvotes: 1
Reputation:
I think this is much more 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
Upvotes: 278
Reputation: 3578
Using lodash:
import _ from 'lodash';
const toBoolean = (val) => _.isEqual(_.toLower(val), 'true');
const values = [0, 1, '', undefined, null, [], {}, new Date(), true, false, 'true', 'false', 'True', 'False'];
_.forEach(values, (value) => {
console.log(`${value} : ${toBoolean(value)}`);
});
https://replit.com/@tokra1/toBoolean-w-Lodash?v=1
Upvotes: 0
Reputation: 2111
Best performance according to https://stackoverflow.com/a/28588344/7333766
Type safe and strict answer (great if you want to enforce stricter rules on your inputs) that I did not see in all other answers, also gives you a clear explanation in the console when it gets an incorrect input:
Typescript version:
function parseBool(value: any):boolean {
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Arrow function version:
const parseBool = (value: any):boolean => {
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Javascript version:
function parseBool(value){
if (value === 'true') return true
if (value === 'false') return false
console.error('parseBool got an unexpected value:', value, '(accepted values : "true", "false")')
throw new Error('Error: parseBool got unexpected value')
}
Upvotes: 6
Reputation: 1312
function parseBool(value: any, defaultsOnUndefined?: boolean) {
if (['true', true, 1, '1', 'yes'].includes(value)) {
return true;
}
if (['false', false, 0, '0', 'no', null].includes(value)) {
return false;
}
return defaultsOnUndefined;
}
OR
function parseBool(value: any) {
if (['true', true, 1, '1', 'yes'].includes(value)) {
return true;
}
return false;
}
Upvotes: 2
Reputation: 19
If you are using Environment Variables, use the following. Works on Heroku. Environment variables are string values that has to be converted to boolean values.
// Create the database connection
this.connection = new Sequelize({
username: process.env.PG_USERNAME,
password: process.env.PG_PASSWORD,
database: process.env.PG_DATABASE,
host: process.env.PG_HOST,
port: process.env.PG_PORT,
dialect: process.env.PG_DIALECT,
dialectOptions: {
ssl: {
require: process.env.PG_DIALECT_OPTION_SSL_REQUIRED === 'true', // <<< convert from string to bool
rejectUnauthorized:
process.env.PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED === 'true', // <<< convert from string to bool
},
},
logging: true,
});
env file
# PostgreSQL Config
PG_USERNAME=ttubkcug
PG_PASSWORD=ea59cee2883e73c602e6c05b674cf16950d6a9f05ab
PG_DATABASE=d67potesdliv25
PG_HOST=ec2-23-333-45-192.compute-1.amazonaws.com
PG_PORT=5432
PG_DIALECT=postgres
PG_DIALECT_OPTION_SSL_REQUIRED=true
PG_DIALECT_OPTION_SSL_REJECT_UNAUTHORIZED=false
Upvotes: 0
Reputation: 1681
function isTrue(val) {
try {
return !!JSON.parse(val);
} catch {
return false;
}
}
Upvotes: 6
Reputation: 19127
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 and security implications when using eval()
though.
Upvotes: 35
Reputation: 82306
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, strict)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if (str == null)
{
if (strict)
throw new Error("Parameter 'str' is null or undefined.");
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]));}
Upvotes: 88
Reputation: 334
In typescript, a small function to handle if the value was passed as a string, number or a boolean e.g. 'true', 'false', true, false, 1, or 0.
const getAsBoolean = (value: string | boolean | number) => {
if (typeof value === 'string') {
return value === 'true';
} else if (typeof value === 'boolean' || typeof value === 'number') {
return Boolean(value);
} else {
return undefined;
}
};
Upvotes: 3
Reputation:
const stringToBoolean = (stringValue) => {
switch(stringValue?.toLowerCase()?.trim()){
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
case undefined:
return false;
default:
return JSON.parse(stringValue);
}
}
Upvotes: 301
Reputation: 109
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.
Upvotes: -1
Reputation: 1179
const string = "false"
const string2 = "true"
const test = (val) => (val === "true" || val === "True")
console.log(test(string))
console.log(test(string2))
Upvotes: 1
Reputation: 864
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);
Upvotes: 167
Reputation: 3764
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
, ''
).
Upvotes: 15
Reputation: 2770
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();
Upvotes: 4
Reputation: 71
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.
Upvotes: 2
Reputation: 798
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")
Upvotes: 6
Reputation: 341
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);
Upvotes: 1
Reputation: 4547
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
Upvotes: 19
Reputation: 1221
// Try this in two ways convert a string to boolean
const checkBoolean = Boolean("false");
const checkBoolean1 = !!"false";
console.log({checkBoolean, checkBoolean1});
Upvotes: -6