regexLiterals
Use a regular expression literal when the pattern is static.
✅ This rule is included in the tslogicalandlogicalStrictpresets.
When the pattern and flags are static strings, using a regex literal is more concise and avoids unnecessary constructor calls. Regex literals are also easier to read and cannot throw at runtime due to invalid patterns, since they are validated at parse time.
Examples
Section titled “Examples”const const pattern: RegExp
pattern = var RegExp: RegExpConstructor(pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("abc");const const pattern: RegExp
pattern = new var RegExp: RegExpConstructornew (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("abc", "gi");const const pattern: RegExp
pattern = var RegExp: RegExpConstructor(pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("");const const pattern: RegExp
pattern = /abc/;const const pattern: RegExp
pattern = /abc/gi;const const pattern: RegExp
pattern = /(?:)/;// Dynamic patterns are fineconst const pattern: RegExp
pattern = new var RegExp: RegExpConstructornew (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp(const userInput: string
userInput);// Dynamic flags are fineconst const pattern: RegExp
pattern = new var RegExp: RegExpConstructornew (pattern: RegExp | string, flags?: string) => RegExp (+2 overloads)
RegExp("abc", const flags: string
flags);Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you prefer to always use RegExp constructors for consistency, or if you are building patterns from static pieces that are easier to read as strings, you might prefer to disable this rule.
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
useRegexLiterals - ESLint:
prefer-regex-literals
Made with ❤️🔥 around the world by
the Flint team and contributors.