snippetjavascriptTip
Convert a string to a boolean
Viewed 0 times
booleanstringjavascriptconvert
Problem
Sometimes, one might run into the problem of converting the string representation of a value into the value itself. This is often straightforward, such as with numeric values. However, string representations of boolean values can be a bit trickier.
This issue arises due to the fact that any non-empty string is considered truthy in JavaScript. On top of that, strings can have different capitalization or whitespace, making it harder to compare them directly to a constant.
@You might also like
To counteract this, it's often a good idea to use a couple of transformations, namely
This issue arises due to the fact that any non-empty string is considered truthy in JavaScript. On top of that, strings can have different capitalization or whitespace, making it harder to compare them directly to a constant.
@You might also like
To counteract this, it's often a good idea to use a couple of transformations, namely
String.prototype.toLowerCase() and String.prototype.trim(), to make the string representation of the value more consistent. Additionally, an array of acceptable values might make it easier to perform the conversion in certain cases.Solution
const toBoolean = (value, truthyValues = ['true']) => {
const normalizedValue = String(value).toLowerCase().trim();
return truthyValues.includes(normalizedValue);
};
toBoolean('true'); // true
toBoolean('TRUE'); // true
toBoolean('True'); // true
toBoolean('tRue '); // true
toBoolean('false'); // false
toBoolean('FALSE'); // false
toBoolean('False'); // false
toBoolean('fAlse '); // false
toBoolean('YES', ['yes']); // true
toBoolean('no', ['yes']); // false@You might also like
To counteract this, it's often a good idea to use a couple of transformations, namely
String.prototype.toLowerCase() and String.prototype.trim(), to make the string representation of the value more consistent. Additionally, an array of acceptable values might make it easier to perform the conversion in certain cases.Code Snippets
const toBoolean = (value, truthyValues = ['true']) => {
const normalizedValue = String(value).toLowerCase().trim();
return truthyValues.includes(normalizedValue);
};
toBoolean('true'); // true
toBoolean('TRUE'); // true
toBoolean('True'); // true
toBoolean('tRue '); // true
toBoolean('false'); // false
toBoolean('FALSE'); // false
toBoolean('False'); // false
toBoolean('fAlse '); // false
toBoolean('YES', ['yes']); // true
toBoolean('no', ['yes']); // falseContext
From 30-seconds-of-code: string-to-boolean
Revisions (0)
No revisions yet.