Parse a boolean from a string in Javascript
Javascript has parseInt built in to help us get a numeric value from a number cast a string. It's incredibly handy when shuffling around data.
Recently, I've dealt with a situation where I needed to get a boolean value set as a data attribute on a DOM object where the value was set as a string ("true" or "false").
Why isn't there an easy way to convert a string to a boolean in Javascript? I'm not sure, and I wasn't satisfied with the answers I found on StackOverflow. So I made a sweet little function to do just this. Coffeescript and compiled JS below:
window.parseBoolean = (string) ->
bool = switch
when string.toLowerCase() == 'true' then true
when string.toLowerCase() == 'false' then false
return bool if typeof bool == "boolean"
return undefined
window.parseBoolean = function(string) {
var bool;
bool = (function() {
switch (false) {
case string.toLowerCase() !== 'true':
return true;
case string.toLowerCase() !== 'false':
return false;
}
})();
if (typeof bool === "boolean") {
return bool;
}
return void 0;
};Written by Eric D. Fields
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside