Skip to content

Instantly share code, notes, and snippets.

@an-ivannikov
Created August 22, 2020 16:05
Show Gist options
  • Save an-ivannikov/ef812226c7d76b8a86bfbc694bfec7cd to your computer and use it in GitHub Desktop.
Save an-ivannikov/ef812226c7d76b8a86bfbc694bfec7cd to your computer and use it in GitHub Desktop.
JS String to Boolean
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