Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A RegExp in TypeScript is an object representing a regular expression, utilized for pattern matching and text manipulation within strings. TypeScript provides static typing over the native JavaScript RegExp implementation through built-in interfaces such as RegExp, RegExpMatchArray, and RegExpExecArray, ensuring type safety when interacting with match results, indices, and capture groups.

Instantiation

Regular expressions in TypeScript can be instantiated using either literal syntax or the RegExp constructor. The literal syntax is compiled when the script is loaded, whereas the constructor is compiled at runtime.
// Literal syntax
const literalRegex: RegExp = /^[a-z]+$/i;

// Constructor syntax
const constructorRegex: RegExp = new RegExp('^[a-z]+$', 'i');

// Constructor with dynamic string
const dynamicPattern: string = "^[a-z]+$";
const dynamicRegex: RegExp = new RegExp(dynamicPattern, 'i');

TypeScript Core Interfaces

TypeScript defines specific return types for regular expression operations to handle the complex arrays returned by the underlying JavaScript engine.
  • RegExp: The interface representing the regular expression instance.
  • RegExpExecArray: An array type returned by RegExp.prototype.exec(). It extends Array<string> and includes the required properties index (number) and input (string), alongside an optional groups property ({ [key: string]: string } | undefined) which is populated only when named capture groups are present.
  • RegExpMatchArray: An array type returned by String.prototype.match(). It extends Array<string> but differs from RegExpExecArray by typing the index and input properties as optional (index?: number, input?: string). This distinction accounts for the runtime behavior where match() omits these properties when the global (g) flag is applied.
const pattern: RegExp = /(?<vowel>[aeiou])/g;
const text: string = "hello";

// exec() returns RegExpExecArray | null
const execResult: RegExpExecArray | null = pattern.exec(text);

if (execResult !== null) {
    const fullMatch: string = execResult[0];        // "e"
    const capture: string = execResult[1];          // "e"
    const index: number = execResult.index;         // 1
    const input: string = execResult.input;         // "hello"
    
    // groups is typed as { [key: string]: string } | undefined
    const namedGroup: string | undefined = execResult.groups?.vowel; 
}

RegExp Instance Methods

The RegExp object exposes two primary methods for pattern evaluation. test() Evaluates the string against the pattern and returns a boolean indicating whether a match exists.
const regex: RegExp = /\d+/;
const isMatch: boolean = regex.test("TypeScript 5"); // true
exec() Executes a search for a match in a specified string. Returns a RegExpExecArray if successful, or null if it fails. When the g (global) or y (sticky) flags are present, exec() updates the lastIndex property of the RegExp instance, allowing for stateful iteration.
const globalRegex: RegExp = /[a-z]/g;
const str: string = "ab";

let match: RegExpExecArray | null;
while ((match = globalRegex.exec(str)) !== null) {
    console.log(`Found ${match[0]} at ${match.index}. Next start: ${globalRegex.lastIndex}`);
}

String Methods Utilizing RegExp

TypeScript strongly types the String prototype methods that accept RegExp arguments.
const target: string = "TS 5.0";
const regex: RegExp = /\d\.\d/;

// match: Returns RegExpMatchArray | null
const matched: RegExpMatchArray | null = target.match(regex);

// matchAll: Returns an IterableIterator of RegExpMatchArray. Requires 'g' flag.
const allMatches: IterableIterator<RegExpMatchArray> = target.matchAll(new RegExp(regex, 'g'));

// replace: Accepts RegExp and a replacement string or replacer function
const replacedStr: string = target.replace(regex, "X.X");
const replacedFn: string = target.replace(regex, (substring: string, ...args: any[]) => "X.X");

// search: Returns the index of the first match, or -1
const searchIndex: number = target.search(regex);

// split: Returns an array of strings split by the RegExp pattern
const splitArr: string[] = target.split(/\s+/);

Flags and Modifiers

TypeScript supports standard ECMAScript regular expression flags. The presence of certain flags alters the expected return types or available properties.
  • g (Global): Finds all matches rather than stopping after the first.
  • i (Ignore case): Makes matches case-insensitive.
  • m (Multiline): Changes behavior of ^ and $ to match the start/end of lines.
  • s (DotAll): Allows . to match newline characters.
  • u (Unicode): Treats patterns as sequences of Unicode code points.
  • y (Sticky): Matches only from the index indicated by the lastIndex property.
  • d (HasIndices): Generates match indices.
The d Flag (Indices) When the d flag is utilized, TypeScript recognizes the indices property on the resulting RegExpExecArray. This requires the es2022.regexp library in the tsconfig.json.
const indicesRegex: RegExp = /foo/d;
const result: RegExpExecArray | null = indicesRegex.exec("foo bar");

if (result && result.indices) {
    // indices is typed as [number, number][]
    const [start, end] = result.indices[0]; 
}
Master TypeScript with Deep Grasping Methodology!Learn More