Skip to content
← Back to rules

eslint/no-invalid-regexp 正确性

This rule is turned on by default.

它的作用

禁止在 RegExp 构造函数中使用无效的正则表达式字符串。

为什么这很糟糕?

正则表达式字面量中的无效模式在解析代码时会抛出 SyntaxError, 但 RegExp 构造函数中的无效字符串只会在代码执行时抛出 SyntaxError。

示例

以下是此规则的错误代码示例:

js
RegExp("[");
RegExp(".", "z");
new RegExp("\\");

以下是此规则的正确代码示例:

js
RegExp(".");
new RegExp();
this.RegExp("[");

配置

此规则接受一个包含以下属性的配置对象:

allowConstructorFlags

type: string[]

default: []

区分大小写的标志数组,将被允许使用。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "no-invalid-regexp": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "no-invalid-regexp": "error",
  },
});
bash
oxlint --deny no-invalid-regexp

版本

此规则新增于 v0.9.4。

参考资料