Regex built on every call
Regex built on every call. Builds the same regex on every call. Compile it once at module level.
This is how the comment reads inline, under the flagged line.
Why it matters
Compiling a regex costs far more than running it. Inside a function or loop, that cost repeats on every call.
What to do
Compile it once as a module-level constant.
Examples
function isSlug(s) {
return new RegExp('^[a-z-]+$').test(s);
}const SLUG = /^[a-z-]+$/;
function isSlug(s) {
return SLUG.test(s);
}What it catches
It reads the shape of the code: functions, blocks, loops and calls. Languages: TypeScript and JavaScript, Python. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.
Flagged
function f(s) {
return new RegExp('a+').test(s);
}
for (const s of xs) {
if (/a+b/.test(s)) n++;
}
src/app.py
import re
def f(s):
return re.compile('a+').match(s)
Left alone
const A = /a+/;
function f(s) {
return A.test(s);
}
src/app.py
import re
A = re.compile('a+')
def f(s):
return A.match(s)
Research
A regex compiled inside a function or loop. The compile cost repeats on every call.
Turn it off or change it
In a config file for the CLI, or in the API's rules field:
{
"rules": {
"disable": [
"regex-in-function"
],
"severity": {
"regex-in-function": "medium"
}
}
}