Languages
[Edit]
EN

JavaScript - convert string to boolean

3 points
Created by:
Kate_C
19790

In JavaScript it is possible to parse string to boolean in following ways.

1. Equality operator example

// ONLINE-RUNNER:browser;

var text = 'true';
var value = (text == 'true');

console.log(value);

2. JSON parse operation example

// ONLINE-RUNNER:browser;

function parseBoolean(text) {
  	var value = JSON.parse(text);

	if(typeof value != 'boolean')
		throw new Error('Incorrect type!');
  
  	return value;
}

var text = 'true';
var value = parseBoolean(text);

console.log(value);

3. 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!');
}

var text = 'true';
var value = parseBoolean(text);

console.log(value);

4. 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!');
    }
}

var text = 'true';
var value = parseBoolean(text);

console.log(value);

 

JavaScript - string conversion

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join