Skip to content

Regex Recompiled In Loop (ARCH3073)

Key typescript.performance.regex-recompiled-in-loop · Severity warning · Category performance

Reconstructing the same regex pattern on every iteration adds needless compilation cost; a constant pattern should be compiled once outside the loop.

function findMatches(lines: string[]): string[] {
const result: string[] = [];
for (const line of lines) {
const re = new RegExp("\\d{3}-\\d{4}");
if (re.test(line)) result.push(line);
}
return result;
}
const PHONE_RE = /\d{3}-\d{4}/;
function findMatches(lines: string[]): string[] {
const result: string[] = [];
for (const line of lines) {
if (PHONE_RE.test(line)) result.push(line);
}
return result;
}

Compile constant regex patterns once outside the loop and reuse them.