How to convert strings like true or false to built-in boolean type JS?
Translation of the question "How can I convert a string to boolean in javascript?"
- association: stackoverflow.com/questions/263965 - user207618
2 answers
let bValue = sValue.toLowerCase().trim() === 'true';
String#toLowerCase and String#trim convert the string to lower case and remove spaces from the end / start.
To successfully convert the values to TRUE , TrUe , True . etc.
If you know exactly what the string will be, you can remove
Beware of the traps of not the most obvious behavior in tricky JS:
let myBool = Boolean("false"); // == true (о_О; не пустая строка (в т. ч. и только пробельные символы) приводится к true) let myBool = !!"false"; // == true (в общем-то одно и то же) Visual explanation of casting .
You can use JSON:
JSON.parse("true"); The plus is that you can feed everything, without checks (for a line, for a format, for spaces, etc), he will check and throw out an error, if there is a minus - to deploy a parser for such a trivial operation is rather strange (although on modern engines the difference is in memory / time will be small).
If the boolean value appears in a different representation ( 1|0 , on|off , hot|cold , etc) and can be any of them, then it is easier to get by with a regular expression:
console.info(['true', 'fFlSe ', ' 1 ', 'OfF', 'hOt'].map(_ => /^(?:true|1|on|hot)$/i.test(_.trim()))); // [true,false,true,false,true] That is, we list all the values that represent true .
A good article on the basics of regular expressions is in wikipedia .
- oneWhy not include whitespace characters in the regular schedule instead of trim? And why the first piece of code in the quote? And remove let let var on var. - Qwertiy ♦
- @Qwertiy, a post specifically for beginners, you should not overload the regular season, probably. - user207618
- @vp_arth, match array of strings will return or null, not a boolean value - Grundy
- oneOkay, I'll change the answer, but don't go away :) - user207618
Try eval , don't abuse it.
var a = "true".toLowerCase(); var b = eval(a); Now a == true .
- oneDon't use evil! - user207618
- @Other eval is evil, but in this case you can use it - Vlad Gavriuk
- Why is it meaningless to load the interpreter? And to teach beginners bad manners? - user207618
- @Other I wrote not to abuse eval . - Vlad Gavriuk
- Abuse - use something when you can do without it. It turns out you are abusing, but recommend others not to abuse. - user207618