EN
JavaScript - convert string to boolean
6
points
In this article, we would like to show you how to parse a string to a boolean in JavaScript
Quick solution:
// ONLINE-RUNNER:browser;
var text = 'true';
console.log(text === 'true'); // true
JSON parse example
// ONLINE-RUNNER:browser;
function parseBoolean(text) {
var value = JSON.parse(text);
if(typeof value !== 'boolean') {
throw new Error('Incorrect type!');
}
return value;
}
// Usage example:
var text = 'true';
var value = parseBoolean(text);
console.log(value); // true
Regular expression example
// ONLINE-RUNNER:browser;
var truthExpression = /^(TRUE|True|true|YES|Yes|yes|ON|On|on|1|T|t|Y|y)$/g;
var falsyExpression = /^(FALSE|False|false|NO|No|no|OFF|Off|off|0|F|f|N|n)$/g;
function parseBoolean(text) {
if (truthExpression.test(text)) {
return true;
}
if (falsyExpression.test(text)) {
return false;
}
throw new Error('Incorrect value!');
}
// Usage example:
var text = 'true';
var value = parseBoolean(text);
console.log(value); // true
Custom function example
// ONLINE-RUNNER:browser;
function parseBoolean(value) {
switch(value) {
case 1:
case true:
case "1":
case "true":
case "True":
case "TRUE":
case "on":
case "On":
case "ON":
case "yes":
case "Yes":
case "YES":
case "t":
case "T":
case "y":
case "Y":
return true;
case 0:
case false:
case "0":
case "false":
case "False":
case "FALSE":
case "off":
case "Off":
case "OFF":
case "no":
case "No":
case "NO":
case "f":
case "F":
case "n":
case "N":
return false;
default:
throw new Error('Incorrect value!');
}
}
// Usage example:
var text = 'true';
var value = parseBoolean(text);
console.log(value); // true