Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - convert string to boolean

0 contributions
3 points

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);

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey đź‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more