Regular Expressions in TypeScript: From Theory to Practice
\nRegular expressions (RegExp) are a powerful tool for searching, replacing, and validating strings. In TypeScript, they work the same as in JavaScript but add strict typing, which simplifies debugging and increases code reliability. In this article, we will break down the syntax, methods, and real-world examples of using regular expressions in TypeScript.
\n\nCreating Regular Expressions in TypeScript
\nIn TypeScript, there are two ways to create a RegExp: literal and via the constructor. Both options are typed and return an object of type RegExp.
Literal Syntax
\nThe simplest and most commonly used method is to enclose the pattern in forward slashes. Flags are specified after the second slash.
\n// Search for the word "hello" case-insensitively\nconst pattern: RegExp = /hello/i;\nconsole.log(pattern.test('Hello World')); // true\n\nRegExp Constructor
\nThe constructor is convenient when the pattern is formed dynamically. The first argument is a string with the pattern, the second is flags.
\nconst searchTerm: string = 'TypeScript';\nconst dynamicPattern: RegExp = new RegExp(searchTerm, 'gi');\nconsole.log('I love TypeScript and TypeScript is great'.match(dynamicPattern));\n// ['TypeScript', 'TypeScript']\n\nBasic RegExp Methods in TypeScript
\nTypeScript inherits all JavaScript methods for working with regex. Let's look at the most popular ones.
\n\ntest() — Checking for a Match
\nThe test() method returns true or false. It is useful for form validation.
const emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\nconst email: string = 'user@example.com';\nconsole.log(emailRegex.test(email)); // true\n\nexec() — Detailed Search
\nexec() returns an array with the match, index, and groups. If there are no matches, it returns null.
const datePattern: RegExp = /(\\d{2})\\.(\\d{2})\\.(\\d{4})/;\nconst result: RegExpExecArray | null = datePattern.exec('Today is 15.03.2025');\nif (result) {\n console.log(`Day: ${result[1]}, Month: ${result[2]}, Year: ${result[3]}`);\n // Day: 15, Month: 03, Year: 2025\n}\n\nmatch() and matchAll() for Strings
\nThe match() method is called on a string and takes a RegExp. For a global search of all matches, use matchAll().
const text: string = 'Code 123, code 456, code 789';\nconst numbers: RegExpMatchArray | null = text.match(/\\d+/g);\nconsole.log(numbers); // ['123', '456', '789']\n\n// matchAll() returns an iterator\nconst matches: IterableIterator<RegExpMatchArray> = text.matchAll(/(\\d+)/g);\nfor (const match of matches) {\n console.log(`Found number: ${match[1]}`);\n}\n\nPractical Examples of Regular Expressions in TypeScript
\nNow let's apply the theory to real-world tasks. All examples are written with TypeScript's strict typing in mind.
\n\nExample 1: Email Address Validation
\nLet's create a function that checks the validity of an email. We'll use a typed regular expression.
\nfunction isValidEmail(email: string): boolean {\n const emailRegex: RegExp = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n return emailRegex.test(email);\n}\n\nconsole.log(isValidEmail('test@mail.ru')); // true\nconsole.log(isValidEmail('invalid-email')); // false\n\nExample 2: Extracting Numbers from a String
\nOften you need to get all numbers from text. We'll use a global search with the g flag.
function extractNumbers(text: string): number[] {\n const numberPattern: RegExp = /\\d+/g;\n const matches: RegExpMatchArray | null = text.match(numberPattern);\n return matches ? matches.map(Number) : [];\n}\n\nconst result: number[] = extractNumbers('Price: 2500 rub, discount 300 rub');\nconsole.log(result); // [2500, 300]\n\