Regular Expressions in TypeScript: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to Regular Expressions in TypeScript



Regular expressions (regex) are a powerful tool for searching, replacing, and validating strings. In TypeScript, as in JavaScript, they are implemented through the built-in RegExp object. However, TypeScript adds strict typing, which makes working with regular expressions safer and more predictable. In this article, we will cover the syntax, methods, typing, and practical examples of using regular expressions in TypeScript.



What is a Regular Expression?

A regular expression is a sequence of characters that defines a search pattern. In TypeScript, regular expressions are created in two ways:

  • Literal syntax: const regex: RegExp = /\\d+/g;
  • RegExp constructor: const regex: RegExp = new RegExp('\\\\d+', 'g');

The second method is useful when the pattern is dynamically formed from variables.



Basic Methods for Working with Regular Expressions in TypeScript



1. The test() method — checking for a match

The test() method returns a boolean — whether there is a match in the string.

const emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;const email: string = 'user@example.com';

if (emailRegex.test(email)) { console.log('Email is valid');} else { console.log('Email is invalid');}// Output: Email is valid


2. The exec() method — getting match details

The exec() method returns a RegExpExecArray | null object. It contains the match, capturing groups, and the position in the string.

const dateRegex: RegExp = /(\\d{2})\\.(\\d{2})\\.(\\d{4})/;const dateString: string = 'Date: 15.03.2023';const match: RegExpExecArray | null = dateRegex.exec(dateString);

if (match) { console.log(`Day: ${match[1]}, Month: ${match[2]}, Year: ${match[3]}`); // Output: Day: 15, Month: 03, Year: 2023}


3. The match() method — searching for all matches in a string

The string method match() takes a regular expression and returns an array of matches or null.

const text: string = 'Cats and kittens are the best!';const catRegex: RegExp = /[Cc]ats?|[Kk]ittens?/g;const matches: RegExpMatchArray | null = text.match(catRegex);

if (matches) { console.log(matches); // ['Cats', 'kittens']}


4. The replace() method — replacement by pattern

The replace() method replaces matches with a specified string or the result of a function.

const phone: string = '+7 (123) 456-78-90';const cleanPhone: string = phone.replace(/[\\s\\-\\(\\)\\+]/g, '');console.log(cleanPhone); // 71234567890

// Replacement using capturing groupsconst name: string = 'Ivanov Ivan';const reversed: string = name.replace(/(\\w+)\\s(\\w+)/, '$2 $1');console.log(reversed); // Ivan Ivanov


5. The split() method — splitting a string

A regular expression can be used to split a string into parts.

const data: string = 'apple;pear,orange:banana';const fruits: string[] = data.split(/[;,.:]/);console.log(fruits); // ['apple', 'pear', 'orange', 'banana']


Typing Regular Expressions in TypeScript



TypeScript automatically infers the variable type as RegExp when using literal syntax. However, in complex projects, an explicit type annotation may be required:

// Explicit type annotationconst hexColor: RegExp = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

// Typing for a function returning RegExpfunction createUrlRegex(baseUrl: string): RegExp { return new RegExp(`^${baseUrl}/[a-z]+$`, 'i');}

const myRegex: RegExp = createUrlRegex('https://example.com');console.log(myRegex.test('ht

Blogs

Book Recommendations