-
-
Save Uvacoder/c1ab15d3f56ceeb183ed9badacfe48fe to your computer and use it in GitHub Desktop.
Convert a string to the equivalent boolean
This file contains hidden or 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