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:

JavaScript
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

Similar Reads

1. Using the ‘+’ unary operator

The unary plus operator (`+`) in TypeScript converts a string to a number by parsing its content. It coerces the string representation of numeric characters into a numerical value, ensuring type conversion....

2. Using Number() method

The Number() method in TypeScript converts a string to a number by explicitly invoking the Number constructor. It parses the string’s content to a numerical value, ensuring type conversion....

3. Using parseFloat() function

The parseFloat() function in TypeScript converts a string to a floating-point number by parsing its content. It extracts and interprets the numerical portion of the string, ensuring type conversion....

4. Using Number.parseInt()

The Number.parseInt() method parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). It’s particularly useful when you want to convert a string to an integer, optionally with a specified radix....

5. Using String.prototype.charCodeAt() and Array.prototype.reduce()

We can leverage the charCodeAt() method along with the reduce() method of arrays to convert a string representing a numeric value to a number in TypeScript. This approach involves converting each character of the string to its Unicode code point and then reconstructing the numeric value based on these code points....

6. Using Regular Expressions

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....