Regex Recompiled In Loop (ARCH3073)
Ce contenu n’est pas encore disponible dans votre langue.
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.
Incorrect
Section titled “Incorrect”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;}Correct
Section titled “Correct”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.