fpbkeg
Last Updated: February 25, 2016
·
12.03K
· ericdfields
H4lny5ny normal

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;
};
Say Thanks
Respond

1 Response
Add your response

24624

its easy and better way to check string value manually. following post explains about it
http://www.coding-issues.com/2015/11/convert-string-to-boolean-in-javascript.html

over 1 year ago ·