UNPKG

@kumarshanu/string-to-boolean

Version:

it converts a given string value to a boolean value. It handles various cases such as 'true', 'false', 'yes', 'no', '1', '0', null, and undefined. It uses a switch statement with case-insensitive comparisons to determine the boolean value. If none of the

30 lines (27 loc) 657 B
function stringToBoolean(stringValue: string | null | undefined): boolean { if (stringValue) { const lowerCaseValue = stringValue.toLowerCase().trim(); if ( lowerCaseValue === 'true' || lowerCaseValue === 'yes' || lowerCaseValue === '1' ) { return true; } else if ( lowerCaseValue === 'false' || lowerCaseValue === 'no' || lowerCaseValue === '0' ) { return false; } else { try { return JSON.parse(stringValue); } catch (error) { throw new Error('Invalid boolean string'); } } } else { return false; } } export default stringToBoolean;