How to use Regular Expressions In Typescript
Regular expressions provide a powerful tool for pattern matching and manipulation in TypeScript. By leveraging regular expressions, we can extract numerical values from strings and convert them to numbers.
Example:
let str: string = "The price is $25.99";
console.log(typeof str); // Output: string
// Extracting numerical values using regular expression
let num: number = parseFloat(str.match(/\d+\.\d+/)[0]);
console.log(`${num} is of type: ${typeof num}`); // Output: 25.99 is of type: number
Output:
25.99 is of type: number
How to convert string to number in TypeScript ?
In typescript, there are numerous ways to convert a string to a number. We can use the ‘+’ unary operator , Number(), parseInt() or parseFloat() function to convert string to number. Let’s demonstrate using a few examples.
Table of Content
- Using the ‘+’ unary operator
- Using Number() method
- Using parseFloat() function
- Using Number.parseInt()
- Using String.prototype.charCodeAt() and Array.prototype.reduce()
- Using Regular Expressions