How to use Regular Expressions In Typescript
In this approach, we employ regular expressions to match common boolean representations within the input string. By defining patterns for boolean values like “true”, “false”, “yes”, “no”, “1”, and “0”, we can accurately determine the boolean equivalent of the input string.
Syntax:
function stringToBoolean(str: string): boolean {
const truePattern: RegExp = /^(true|yes|1)$/i;
const falsePattern: RegExp = /^(false|no|0)$/i;
if (truePattern.test(str)) {
return true;
} else if (falsePattern.test(str)) {
return false;
} else {
throw new Error('Invalid boolean string');
}
}
Example: The following example demonstrates how to use regular expressions to convert a string to a boolean in TypeScript.
function stringToBoolean(str: string): boolean {
const truePattern: RegExp = /^(true|yes|1)$/i;
const falsePattern: RegExp = /^(false|no|0)$/i;
if (truePattern.test(str)) {
return true;
} else if (falsePattern.test(str)) {
return false;
} else {
throw new Error('Invalid boolean string');
}
}
const result1: boolean = stringToBoolean('True');
console.log(result1); // Output: true
const result2: boolean = stringToBoolean('no');
console.log(result2); // Output: false
Output:
true
false
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it.
There are several approaches to convert string to boolean in TypeScript which are as follows:
Table of Content
- Using Conditional Statement
- Using JSON.parse() Method
- Using Type Assertion
- Using Regular Expressions