JavaScript has parseInt()
and parseFloat()
, but there's no parseBool
or parseBoolean
method in the global scope, as far as I'm aware.
I need a method that takes strings with values like "true" or "false" and returns a JavaScript Boolean
.
Here's my implementation:
function parseBool(value) {
return (typeof value === "undefined") ?
false :
// trim using jQuery.trim()'s source
value.replace(/^\s+|\s+$/g, "").toLowerCase() === "true";
}
Is this a good function? Please give me your feedback.
Thanks!
This question is related to
javascript
trim
Personally I think it's not good, that your function "hides" invalid values as false
and - depending on your use cases - doesn't return true
for "1"
.
Another problem could be that it barfs on anything that's not a string.
I would use something like this:
function parseBool(value) {
if (typeof value === "string") {
value = value.replace(/^\s+|\s+$/g, "").toLowerCase();
if (value === "true" || value === "false")
return value === "true";
}
return; // returns undefined
}
And depending on the use cases extend it to distinguish between "0"
and "1"
.
(Maybe there is a way to compare only once against "true"
, but I couldn't think of something right now.)
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
You can try the following:
function parseBool(val)
{
if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
return true;
else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
return false;
return null;
}
If it's a valid value, it returns the equivalent bool value otherwise it returns null.
I shamelessly converted Apache Common's toBoolean
to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {_x000D_
if (str == "true") {_x000D_
return true;_x000D_
}_x000D_
if (!str) {_x000D_
return false;_x000D_
}_x000D_
switch (str.length) {_x000D_
case 1: {_x000D_
var ch0 = str.charAt(0);_x000D_
if (ch0 == 'y' || ch0 == 'Y' ||_x000D_
ch0 == 't' || ch0 == 'T' ||_x000D_
ch0 == '1') {_x000D_
return true;_x000D_
}_x000D_
if (ch0 == 'n' || ch0 == 'N' ||_x000D_
ch0 == 'f' || ch0 == 'F' ||_x000D_
ch0 == '0') {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 2: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'n' || ch1 == 'N') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'n' || ch0 == 'N') &&_x000D_
(ch1 == 'o' || ch1 == 'O') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 3: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
if ((ch0 == 'y' || ch0 == 'Y') &&_x000D_
(ch1 == 'e' || ch1 == 'E') &&_x000D_
(ch2 == 's' || ch2 == 'S') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'f' || ch1 == 'F') &&_x000D_
(ch2 == 'f' || ch2 == 'F') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 4: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
if ((ch0 == 't' || ch0 == 'T') &&_x000D_
(ch1 == 'r' || ch1 == 'R') &&_x000D_
(ch2 == 'u' || ch2 == 'U') &&_x000D_
(ch3 == 'e' || ch3 == 'E') ) {_x000D_
return true;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 5: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
var ch4 = str.charAt(4);_x000D_
if ((ch0 == 'f' || ch0 == 'F') &&_x000D_
(ch1 == 'a' || ch1 == 'A') &&_x000D_
(ch2 == 'l' || ch2 == 'L') &&_x000D_
(ch3 == 's' || ch3 == 'S') &&_x000D_
(ch4 == 'e' || ch4 == 'E') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
default:_x000D_
break;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
console.log(toBoolean("yEs")); // true_x000D_
console.log(toBoolean("yES")); // true_x000D_
console.log(toBoolean("no")); // false_x000D_
console.log(toBoolean("NO")); // false_x000D_
console.log(toBoolean("on")); // true_x000D_
console.log(toBoolean("oFf")); // false
_x000D_
Inspect this element, and view the console output.
_x000D_
Why not keep it simple?
var parseBool = function(str) {
if (typeof str === 'string' && str.toLowerCase() == 'true')
return true;
return (parseInt(str) > 0);
}
last but not least, a simple and efficient way to do it with a default value :
ES5
function parseBool(value, defaultValue) {
return (value == 'true' || value == 'false' || value === true || value === false) && JSON.parse(value) || defaultValue;
}
ES6 , a shorter one liner
const parseBool = (value, defaultValue) => ['true', 'false', true, false].includes(value) && JSON.parse(value) || defaultValue
JSON.parse is efficient to parse booleans
It depends how you wish the function to work.
If all you wish to do is test for the word 'true' inside the string, and define any string (or nonstring) that doesn't have it as false, the easiest way is probably this:
function parseBoolean(str) {
return /true/i.test(str);
}
If you wish to assure that the entire string is the word true you could do this:
function parseBoolean(str) {
return /^true$/i.test(str);
}
stringjs has a toBoolean() method:
http://stringjs.com/#methods/toboolean-tobool
S('true').toBoolean() //true
S('false').toBoolean() //false
S('hello').toBoolean() //false
S(true).toBoolean() //true
S('on').toBoolean() //true
S('yes').toBoolean() //true
S('TRUE').toBoolean() //true
S('TrUe').toBoolean() //true
S('YES').toBoolean() //true
S('ON').toBoolean() //true
S('').toBoolean() //false
S(undefined).toBoolean() //false
S('undefined').toBoolean() //false
S(null).toBoolean() //false
S(false).toBoolean() //false
S({}).toBoolean() //false
S(1).toBoolean() //true
S(-1).toBoolean() //false
S(0).toBoolean() //false
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
I would be inclined to do a one liner with a ternary if.
var bool_value = value == "true" ? true : false
Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:
var bool_value = value == 'true';
This works because value == 'true'
is evaluated based on whether the value
variable is a string of 'true'
. If it is, that whole expression becomes true
and if not, it becomes false
, then that result gets assigned to bool_value
after evaluation.
I like the solution provided by RoToRa (try to parse given value, if it has any boolean meaning, otherwise - don't). Nevertheless I'd like to provide small modification, to have it working more or less like Boolean.TryParse in C#, which supports out
params. In JavaScript it can be implemented in the following manner:
var BoolHelpers = {
tryParse: function (value) {
if (typeof value == 'boolean' || value instanceof Boolean)
return value;
if (typeof value == 'string' || value instanceof String) {
value = value.trim().toLowerCase();
if (value === 'true' || value === 'false')
return value === 'true';
}
return { error: true, msg: 'Parsing error. Given value has no boolean meaning.' }
}
}
The usage:
var result = BoolHelpers.tryParse("false");
if (result.error) alert(result.msg);
You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:
function test (input) {
try {
return !!$.parseJSON(input.toLowerCase());
} catch (e) { }
}
Wood-eye be careful. After looking at all this code, I feel obligated to post:
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')
{
if(str === true)
return true;
return false;
}
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]));}
Enough to using eval javascript function to convert string to boolean
eval('true')
eval('false')
Source: Stackoverflow.com