Regular Expressions in TypeScript: Syntax, Methods, and Examples
Regular expressions (regex) are a powerful tool for working with strings. In TypeScript, they allow you not only to search, replace, and validate text but also to get strict typing of results. In this article, we will cover all aspects of working with RegExp in TypeScript: from basic syntax to advanced techniques with code examples.
1. Creating Regular Expressions in TypeScript
In TypeScript, as in JavaScript, there are two ways to create a regular expression:
Literal Syntax
The most common and convenient way is to use slashes:
const pattern: RegExp = /hello/gi;Here g is global search, i is case-insensitivity. The RegExp type is inferred automatically, but it can be specified explicitly for readability.
RegExp Constructor
Used when the pattern is formed dynamically:
const searchTerm: string = "world";const dynamicPattern: RegExp = new RegExp(searchTerm, "gi");The second argument is a string with flags. The return type is RegExp.
2. Basic RegExp and String Methods
TypeScript inherits all JavaScript methods but adds strict typing to them. Let's look at key methods with examples.
The test() Method
Checks if there is a match in the string. Returns boolean.
const emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;const email: string = "user@example.com";
const isValid: boolean = emailRegex.test(email);console.log(isValid); // trueThe exec() Method
Searches for a match and returns detailed information. Returns RegExpExecArray | null.
const text: string = "Price: 1500 rubles, discount: 200 rubles";const pricePattern: RegExp = /(\\d+)\\s*rubles/g;
let match: RegExpExecArray | null;while ((match = pricePattern.exec(text)) !== null) { console.log(`Found: ${match[0]}, number: ${match[1]}`);}// Output:// Found: 1500 rubles, number: 1500// Found: 200 rubles, number: 200The String match() Method
Works similarly to exec(), but is called on the string. Returns RegExpMatchArray | null.
const phone: string = "Contacts: +7 (999) 123-45-67";const phoneRegex: RegExp = /\\+7\\s*\\(\\d{3}\\)\\s*\\d{3}-\\d{2}-\\d{2}/;
const result: RegExpMatchArray | null = phone.match(phoneRegex);if (result) { console.log(`Phone found: ${result[0]}`); // Phone found: +7 (999) 123-45-67}The replace() Method
Replaces matches with a new string. Returns string. Supports a callback for complex replacements.
function formatDate(input: string): string { const datePattern: RegExp = /(\\d{4})-(\\d{2})-(\\d{2})/; return input.replace(datePattern, "$3.$2.$1");}
const isoDate: string = "2025-03-10";const formatted: string = formatDate(isoDate);console.log(formatted); // "10.03.2025"The split() Method
Splits a string by a regular expression. Returns string[].
const data: string = "apple;pear;orange;banana";const items: string[] = data.split(/;\\s*/);console.log(items); // ["apple", "pear", "orange", "banana"]3. Flags and Their Combinations
Flags control the behavior of the regular expression. In TypeScript, they are set either in the literal or as the second argument of the constructor.
| Flag | Description | Example |
|---|---|---|
g | Global search (all matches) | /ab/g |
i | Case-insensitivity |