1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| var myValue = 'true'; var isTrueSet = (myValue === 'true'); console.log(isTrueSet);
var isTrueSetCaseInsensitive = /^true$/i.test(myValue); console.log(isTrueSetCaseInsensitive);
try { var boolFromJSON = JSON.parse('true'); console.log(boolFromJSON); } catch (error) { console.error(error); }
var array_1 = [true, 1, "1", -1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity", " - Infinity", " yEs"]; var array_2 = [null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc"];
function parseBool(str, strict) { if (str == null) { if (strict) throw new Error("Parameter 'str' is null or undefined."); return false; } if (typeof str === 'boolean') { return (str === true); } if(typeof str === 'string') { if(str == "") return false; str = str.replace(/^\s+|\s+$/g, ''); if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes') return true; str = str.replace(/,/g, '.'); str = str.replace(/^\s*\-\s*/g, '-'); } if(!isNaN(str)) return (parseFloat(str) != 0); return false; }
for(var i = 0; i < array_1.length; ++i) { console.log("array_1[" + i + "] (" + array_1[i] + "): " + parseBool(array_1[i])); }
for(var i = 0; i < array_2.length; ++i) { console.log("array_2[" + i + "] (" + array_2[i] + "): " + parseBool(array_2[i])); }
function strToBool(s) { regex=/^\s*(true|1|on)\s*$/i; return regex.test(s); } console.log(strToBool("true"));
String.prototype.bool = function() { return strToBool(this); }; console.log("true".bool());
const stringToBoolean = (string) => string === 'false' ? false : !!string; console.log(stringToBoolean('true'));
|