Languages
[Edit]
EN

JavaScript - convert string to boolean

6 points
Created by:
a_horse
478

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

 

Alternative titles

  1. JavaScript - parse string to boolean
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - string conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join