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:
xxxxxxxxxx
1
var text = 'true';
2
3
console.log(text === 'true'); // true
xxxxxxxxxx
1
function parseBoolean(text) {
2
var value = JSON.parse(text);
3
if(typeof value !== 'boolean') {
4
throw new Error('Incorrect type!');
5
}
6
return value;
7
}
8
9
10
// Usage example:
11
12
var text = 'true';
13
var value = parseBoolean(text);
14
15
console.log(value); // true
xxxxxxxxxx
1
var truthExpression = /^(TRUE|True|true|YES|Yes|yes|ON|On|on|1|T|t|Y|y)$/g;
2
var falsyExpression = /^(FALSE|False|false|NO|No|no|OFF|Off|off|0|F|f|N|n)$/g;
3
4
function parseBoolean(text) {
5
if (truthExpression.test(text)) {
6
return true;
7
}
8
if (falsyExpression.test(text)) {
9
return false;
10
}
11
throw new Error('Incorrect value!');
12
}
13
14
15
// Usage example:
16
17
var text = 'true';
18
var value = parseBoolean(text);
19
20
console.log(value); // true
xxxxxxxxxx
1
function parseBoolean(value) {
2
switch(value) {
3
case 1:
4
case true:
5
case "1":
6
case "true":
7
case "True":
8
case "TRUE":
9
case "on":
10
case "On":
11
case "ON":
12
case "yes":
13
case "Yes":
14
case "YES":
15
case "t":
16
case "T":
17
case "y":
18
case "Y":
19
return true;
20
case 0:
21
case false:
22
case "0":
23
case "false":
24
case "False":
25
case "FALSE":
26
case "off":
27
case "Off":
28
case "OFF":
29
case "no":
30
case "No":
31
case "NO":
32
case "f":
33
case "F":
34
case "n":
35
case "N":
36
return false;
37
default:
38
throw new Error('Incorrect value!');
39
}
40
}
41
42
43
// Usage example:
44
45
var text = 'true';
46
var value = parseBoolean(text);
47
48
console.log(value); // true