Created
August 22, 2020 16:05
-
-
Save an-ivannikov/ef812226c7d76b8a86bfbc694bfec7cd to your computer and use it in GitHub Desktop.
JS String to 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) { | |
if (str === undefined) return false; | |
switch (str.toLowerCase().trim()) { | |
case 'true': case 'yes': case '1': return true; | |
case 'false': case 'no': case '0': case null: return false; | |
default: return Boolean(str); | |
} | |
} | |
module.exports = stringToBoolean; | |
/* ExpressJS Example | |
// curl "http://localhost:3000/echo?bool=true" | |
// file ./routes/index.js | |
const express = require('express'); | |
const router = express.Router(); | |
router.get('/echo', async (req, res, next) => { | |
const bool = stringToBoolean(req.query.bool); | |
console.log('bool', bool); | |
return res.json(bool); | |
}); | |
module.exports = router; | |
function stringToBoolean(str) { | |
if (str === undefined) return false; | |
switch (str.toLowerCase().trim()) { | |
case 'true': case 'yes': case '1': return true; | |
case 'false': case 'no': case '0': case null: return false; | |
default: return Boolean(str); | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment