Created
March 5, 2020 09:33
-
-
Save DavidWells/f610459b40e2e4d31691cc155e9e8f2f to your computer and use it in GitHub Desktop.
Convert a string to the equivalent boolean
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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