Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created March 5, 2020 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DavidWells/f610459b40e2e4d31691cc155e9e8f2f to your computer and use it in GitHub Desktop.
Save DavidWells/f610459b40e2e4d31691cc155e9e8f2f to your computer and use it in GitHub Desktop.
Convert a string to the equivalent boolean
function stringToBoolean(str) {
const string = (typeof str === 'string') ? str.toLowerCase().trim() : str
switch (string) {
case "true": case "yes": case "1": return true
case "false": case "no": case "0": case null: return false
default: return Boolean(string)
}
}
// Usage
stringToBoolean('true') // true
stringToBoolean('TRUE') // true
stringToBoolean('yes') // true
stringToBoolean('1') // true
stringToBoolean(true) // true
stringToBoolean('false') // false
stringToBoolean('FALSE') // false
stringToBoolean('no') // false
stringToBoolean('0') // false
stringToBoolean(false) // false
stringToBoolean(null) // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment