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 pattern = RegExp("abc");const pattern = new RegExp("abc", "gi");const pattern = RegExp("");const pattern = /abc/;const pattern = /abc/gi;const pattern = /(?:)/;// Dynamic patterns are fineconst pattern = new RegExp(userInput);// Dynamic flags are fineconst pattern = new RegExp("abc", 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 ❤️🔥 in Boston by
Josh Goldberg and contributors.