I shamelessly converted Apache Common's toBoolean
to JavaScript:
JSFiddle: https://jsfiddle.net/m2efvxLm/1/
Code:
function toBoolean(str) {_x000D_
if (str == "true") {_x000D_
return true;_x000D_
}_x000D_
if (!str) {_x000D_
return false;_x000D_
}_x000D_
switch (str.length) {_x000D_
case 1: {_x000D_
var ch0 = str.charAt(0);_x000D_
if (ch0 == 'y' || ch0 == 'Y' ||_x000D_
ch0 == 't' || ch0 == 'T' ||_x000D_
ch0 == '1') {_x000D_
return true;_x000D_
}_x000D_
if (ch0 == 'n' || ch0 == 'N' ||_x000D_
ch0 == 'f' || ch0 == 'F' ||_x000D_
ch0 == '0') {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 2: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'n' || ch1 == 'N') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'n' || ch0 == 'N') &&_x000D_
(ch1 == 'o' || ch1 == 'O') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 3: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
if ((ch0 == 'y' || ch0 == 'Y') &&_x000D_
(ch1 == 'e' || ch1 == 'E') &&_x000D_
(ch2 == 's' || ch2 == 'S') ) {_x000D_
return true;_x000D_
}_x000D_
if ((ch0 == 'o' || ch0 == 'O') &&_x000D_
(ch1 == 'f' || ch1 == 'F') &&_x000D_
(ch2 == 'f' || ch2 == 'F') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 4: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
if ((ch0 == 't' || ch0 == 'T') &&_x000D_
(ch1 == 'r' || ch1 == 'R') &&_x000D_
(ch2 == 'u' || ch2 == 'U') &&_x000D_
(ch3 == 'e' || ch3 == 'E') ) {_x000D_
return true;_x000D_
}_x000D_
break;_x000D_
}_x000D_
case 5: {_x000D_
var ch0 = str.charAt(0);_x000D_
var ch1 = str.charAt(1);_x000D_
var ch2 = str.charAt(2);_x000D_
var ch3 = str.charAt(3);_x000D_
var ch4 = str.charAt(4);_x000D_
if ((ch0 == 'f' || ch0 == 'F') &&_x000D_
(ch1 == 'a' || ch1 == 'A') &&_x000D_
(ch2 == 'l' || ch2 == 'L') &&_x000D_
(ch3 == 's' || ch3 == 'S') &&_x000D_
(ch4 == 'e' || ch4 == 'E') ) {_x000D_
return false;_x000D_
}_x000D_
break;_x000D_
}_x000D_
default:_x000D_
break;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
console.log(toBoolean("yEs")); // true_x000D_
console.log(toBoolean("yES")); // true_x000D_
console.log(toBoolean("no")); // false_x000D_
console.log(toBoolean("NO")); // false_x000D_
console.log(toBoolean("on")); // true_x000D_
console.log(toBoolean("oFf")); // false
_x000D_
Inspect this element, and view the console output.
_x000D_