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!
Post
Post a tip
Best
#Coffeescript
Authors
iam4x
94.17K
ericdfields
63.02K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#