Skip to content

Instantly share code, notes, and snippets.

@Uvacoder
Forked from DavidWells/string-to-boolean.js
Created January 2, 2022 01:48
Show Gist options
  • Select an option

  • Save Uvacoder/c1ab15d3f56ceeb183ed9badacfe48fe to your computer and use it in GitHub Desktop.

Select an option

Save Uvacoder/c1ab15d3f56ceeb183ed9badacfe48fe 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