# prefer-regex-literals

禁止使用 RegExp 构造函数来支持正则表达式字面

创建正则表达式有两种方法:

  • 正则表达式字面,例如 /abc/u
  • RegExp 构造函数,例如 new RegExp("abc", "u")RegExp("abc", "u")

当您想要动态生成模式时,构造函数特别有用,因为它接受字符串参数。

当使用带有字符串字面的构造函数时,不要忘记字符串转义规则仍然适用。如果要在模式中放置反斜杠,则需要在字符串字面中对其进行转义。因此,以下是等价的:

new RegExp("^\\d\\.$");

/^\d\.$/;

// matches "0.", "1.", "2." ... "9."

在上面的示例中,正则表达式字面更易于阅读和推理。此外,在字符串字面中省略额外的 \ 是一个常见错误,这会产生完全不同的正则表达式:

new RegExp("^\d\.$");

// equivalent to /^d.$/, matches "d1", "d2", "da", "db" ...

当预先知道正则表达式时,最好避免在正则表达式表示法之上使用字符串字面表示法,并使用正则表达式字面而不是构造函数。

# 规则详情

此规则不允许使用 RegExp 构造函数并将字符串字面作为其参数。

此规则还禁止将 RegExp 构造函数与不带表达式的模板字面和不带表达式的 String.raw 标记模板字面一起使用。

该规则并不禁止所有使用 RegExp 构造函数。它仍应用于动态生成的正则表达式。

此规则的错误代码示例:

/*eslint prefer-regex-literals: "error"*/

new RegExp("abc");

new RegExp("abc", "u");

RegExp("abc");

RegExp("abc", "u");

new RegExp("\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d");

RegExp(`^\\d\\.

  prefer-regex-literals - ESLint 中文文档

      #logo_box{background-color: #4B32C3;}
      #logo_box_link{color: #fff;}#logo_img_box{border-color: #fff;}

          ESLint 中文文档

                      新手上路核心概念配置命令行接口规则   array-callback-return   constructor-super   for-direction   getter-return   no-async-promise-executor   no-await-in-loop   no-class-assign   no-compare-neg-zero   no-cond-assign   no-const-assign   no-constant-binary-expression   no-constant-condition   no-constructor-return   no-control-regex   no-debugger   no-dupe-args   no-dupe-class-members   no-dupe-else-if   no-dupe-keys   no-duplicate-case   no-duplicate-imports   no-empty-character-class   no-empty-pattern   no-ex-assign   no-fallthrough   no-func-assign   no-import-assign   no-inner-declarations   no-invalid-regexp   no-irregular-whitespace   no-loss-of-precision   no-misleading-character-class   no-new-symbol   no-obj-calls   no-promise-executor-return   no-prototype-builtins   no-self-assign   no-self-compare   no-setter-return   no-sparse-arrays   no-template-curly-in-string   no-this-before-super   no-undef   no-unexpected-multiline   no-unmodified-loop-condition   no-unreachable   no-unreachable-loop   no-unsafe-finally   no-unsafe-negation   no-unsafe-optional-chaining   no-unused-private-class-members   no-unused-vars   no-use-before-define   no-useless-backreference   require-atomic-updates   use-isnan   valid-typeof   accessor-pairs   arrow-body-style   block-scoped-var   camelcase   capitalized-comments   class-methods-use-this   complexity   consistent-return   consistent-this   curly   default-case   default-case-last   default-param-last   dot-notation   eqeqeq   func-name-matching   func-names   func-style   grouped-accessor-pairs   guard-for-in   id-denylist   id-length   id-match   init-declarations   logical-assignment-operators   max-classes-per-file   max-depth   max-lines   max-lines-per-function   max-nested-callbacks   max-params   max-statements   multiline-comment-style   new-cap   no-alert   no-array-constructor   no-bitwise   no-caller   no-case-declarations   no-confusing-arrow   no-console   no-continue   no-delete-var   no-div-regex   no-else-return   no-empty   no-empty-function   no-eq-null   no-eval   no-extend-native   no-extra-bind   no-extra-boolean-cast   no-extra-label   no-extra-semi   no-floating-decimal   no-global-assign   no-implicit-coercion   no-implicit-globals   no-implied-eval   no-inline-comments   no-invalid-this   no-iterator   no-label-var   no-labels   no-lone-blocks   no-lonely-if   no-loop-func   no-magic-numbers   no-mixed-operators   no-multi-assign   no-multi-str   no-negated-condition   no-nested-ternary   no-new   no-new-func   no-new-object   no-new-wrappers   no-nonoctal-decimal-escape   no-octal   no-octal-escape   no-param-reassign   no-plusplus   no-proto   no-redeclare   no-regex-spaces   no-restricted-exports   no-restricted-globals   no-restricted-imports   no-restricted-properties   no-restricted-syntax   no-return-assign   no-return-await   no-script-url   no-sequences   no-shadow   no-shadow-restricted-names   no-ternary   no-throw-literal   no-undef-init   no-undefined   no-underscore-dangle   no-unneeded-ternary   no-unused-expressions   no-unused-labels   no-useless-call   no-useless-catch   no-useless-computed-key   no-useless-concat   no-useless-constructor   no-useless-escape   no-useless-rename   no-useless-return   no-var   no-void   no-warning-comments   no-with   object-shorthand   one-var   one-var-declaration-per-line   operator-assignment   prefer-arrow-callback   prefer-const   prefer-destructuring   prefer-exponentiation-operator   prefer-named-capture-group   prefer-numeric-literals   prefer-object-has-own   prefer-object-spread   prefer-promise-reject-errors   prefer-regex-literals   prefer-rest-params   prefer-spread   prefer-template   quote-props   radix   require-await   require-unicode-regexp   require-yield   sort-imports   sort-keys   sort-vars   spaced-comment   strict   symbol-description   vars-on-top   yoda   array-bracket-newline   array-bracket-spacing   array-element-newline   arrow-parens   arrow-spacing   block-spacing   brace-style   comma-dangle   comma-spacing   comma-style   computed-property-spacing   dot-location   eol-last   func-call-spacing   function-call-argument-newline   function-paren-newline   generator-star-spacing   implicit-arrow-linebreak   indent   jsx-quotes   key-spacing   keyword-spacing   line-comment-position   linebreak-style   lines-around-comment   lines-between-class-members   max-len   max-statements-per-line   multiline-ternary   new-parens   newline-per-chained-call   no-extra-parens   no-mixed-spaces-and-tabs   no-multi-spaces   no-multiple-empty-lines   no-tabs   no-trailing-spaces   no-whitespace-before-property   nonblock-statement-body-position   object-curly-newline   object-curly-spacing   object-property-newline   operator-linebreak   padded-blocks   padding-line-between-statements   quotes   rest-spread-spacing   semi   semi-spacing   semi-style   space-before-blocks   space-before-function-paren   space-in-parens   space-infix-ops   space-unary-ops   switch-colon-spacing   template-curly-spacing   template-tag-spacing   unicode-bom   wrap-iife   wrap-regex   yield-star-spacing   callback-return   global-require   handle-callback-err   id-blacklist   indent-legacy   lines-around-directive   newline-after-var   newline-before-return   no-buffer-constructor   no-catch-shadow   no-mixed-requires   no-native-reassign   no-negated-in-lhs   no-new-require   no-path-concat   no-process-env   no-process-exit   no-restricted-modules   no-spaced-func   no-sync   prefer-reflect   require-jsdoc   valid-jsdoc   generator-star   global-strict   no-arrow-condition   no-comma-dangle   no-empty-class   no-empty-label   no-extra-strict   no-reserved-keys   no-space-before-semi   no-wrap-func   space-after-function-name   space-after-keywords   space-before-function-parentheses   space-before-keywords   space-in-brackets   space-return-throw-case   space-unary-word-ops   spaced-line-comment格式化器集成迁移到 v8.x

            );

new RegExp(String.raw`^\d\.

  prefer-regex-literals - ESLint 中文文档

      #logo_box{background-color: #4B32C3;}
      #logo_box_link{color: #fff;}#logo_img_box{border-color: #fff;}

          ESLint 中文文档

                      新手上路核心概念配置命令行接口规则   array-callback-return   constructor-super   for-direction   getter-return   no-async-promise-executor   no-await-in-loop   no-class-assign   no-compare-neg-zero   no-cond-assign   no-const-assign   no-constant-binary-expression   no-constant-condition   no-constructor-return   no-control-regex   no-debugger   no-dupe-args   no-dupe-class-members   no-dupe-else-if   no-dupe-keys   no-duplicate-case   no-duplicate-imports   no-empty-character-class   no-empty-pattern   no-ex-assign   no-fallthrough   no-func-assign   no-import-assign   no-inner-declarations   no-invalid-regexp   no-irregular-whitespace   no-loss-of-precision   no-misleading-character-class   no-new-symbol   no-obj-calls   no-promise-executor-return   no-prototype-builtins   no-self-assign   no-self-compare   no-setter-return   no-sparse-arrays   no-template-curly-in-string   no-this-before-super   no-undef   no-unexpected-multiline   no-unmodified-loop-condition   no-unreachable   no-unreachable-loop   no-unsafe-finally   no-unsafe-negation   no-unsafe-optional-chaining   no-unused-private-class-members   no-unused-vars   no-use-before-define   no-useless-backreference   require-atomic-updates   use-isnan   valid-typeof   accessor-pairs   arrow-body-style   block-scoped-var   camelcase   capitalized-comments   class-methods-use-this   complexity   consistent-return   consistent-this   curly   default-case   default-case-last   default-param-last   dot-notation   eqeqeq   func-name-matching   func-names   func-style   grouped-accessor-pairs   guard-for-in   id-denylist   id-length   id-match   init-declarations   logical-assignment-operators   max-classes-per-file   max-depth   max-lines   max-lines-per-function   max-nested-callbacks   max-params   max-statements   multiline-comment-style   new-cap   no-alert   no-array-constructor   no-bitwise   no-caller   no-case-declarations   no-confusing-arrow   no-console   no-continue   no-delete-var   no-div-regex   no-else-return   no-empty   no-empty-function   no-eq-null   no-eval   no-extend-native   no-extra-bind   no-extra-boolean-cast   no-extra-label   no-extra-semi   no-floating-decimal   no-global-assign   no-implicit-coercion   no-implicit-globals   no-implied-eval   no-inline-comments   no-invalid-this   no-iterator   no-label-var   no-labels   no-lone-blocks   no-lonely-if   no-loop-func   no-magic-numbers   no-mixed-operators   no-multi-assign   no-multi-str   no-negated-condition   no-nested-ternary   no-new   no-new-func   no-new-object   no-new-wrappers   no-nonoctal-decimal-escape   no-octal   no-octal-escape   no-param-reassign   no-plusplus   no-proto   no-redeclare   no-regex-spaces   no-restricted-exports   no-restricted-globals   no-restricted-imports   no-restricted-properties   no-restricted-syntax   no-return-assign   no-return-await   no-script-url   no-sequences   no-shadow   no-shadow-restricted-names   no-ternary   no-throw-literal   no-undef-init   no-undefined   no-underscore-dangle   no-unneeded-ternary   no-unused-expressions   no-unused-labels   no-useless-call   no-useless-catch   no-useless-computed-key   no-useless-concat   no-useless-constructor   no-useless-escape   no-useless-rename   no-useless-return   no-var   no-void   no-warning-comments   no-with   object-shorthand   one-var   one-var-declaration-per-line   operator-assignment   prefer-arrow-callback   prefer-const   prefer-destructuring   prefer-exponentiation-operator   prefer-named-capture-group   prefer-numeric-literals   prefer-object-has-own   prefer-object-spread   prefer-promise-reject-errors   prefer-regex-literals   prefer-rest-params   prefer-spread   prefer-template   quote-props   radix   require-await   require-unicode-regexp   require-yield   sort-imports   sort-keys   sort-vars   spaced-comment   strict   symbol-description   vars-on-top   yoda   array-bracket-newline   array-bracket-spacing   array-element-newline   arrow-parens   arrow-spacing   block-spacing   brace-style   comma-dangle   comma-spacing   comma-style   computed-property-spacing   dot-location   eol-last   func-call-spacing   function-call-argument-newline   function-paren-newline   generator-star-spacing   implicit-arrow-linebreak   indent   jsx-quotes   key-spacing   keyword-spacing   line-comment-position   linebreak-style   lines-around-comment   lines-between-class-members   max-len   max-statements-per-line   multiline-ternary   new-parens   newline-per-chained-call   no-extra-parens   no-mixed-spaces-and-tabs   no-multi-spaces   no-multiple-empty-lines   no-tabs   no-trailing-spaces   no-whitespace-before-property   nonblock-statement-body-position   object-curly-newline   object-curly-spacing   object-property-newline   operator-linebreak   padded-blocks   padding-line-between-statements   quotes   rest-spread-spacing   semi   semi-spacing   semi-style   space-before-blocks   space-before-function-paren   space-in-parens   space-infix-ops   space-unary-ops   switch-colon-spacing   template-curly-spacing   template-tag-spacing   unicode-bom   wrap-iife   wrap-regex   yield-star-spacing   callback-return   global-require   handle-callback-err   id-blacklist   indent-legacy   lines-around-directive   newline-after-var   newline-before-return   no-buffer-constructor   no-catch-shadow   no-mixed-requires   no-native-reassign   no-negated-in-lhs   no-new-require   no-path-concat   no-process-env   no-process-exit   no-restricted-modules   no-spaced-func   no-sync   prefer-reflect   require-jsdoc   valid-jsdoc   generator-star   global-strict   no-arrow-condition   no-comma-dangle   no-empty-class   no-empty-label   no-extra-strict   no-reserved-keys   no-space-before-semi   no-wrap-func   space-after-function-name   space-after-keywords   space-before-function-parentheses   space-before-keywords   space-in-brackets   space-return-throw-case   space-unary-word-ops   spaced-line-comment格式化器集成迁移到 v8.x

            );

此规则的正确代码示例:

/*eslint prefer-regex-literals: "error"*/

/abc/;

/abc/u;

/\d\d\.\d\d\.\d\d\d\d/;

/^\d\.$/;

// RegExp constructor is allowed for dynamically generated regular expressions

new RegExp(pattern);

RegExp("abc", flags);

new RegExp(prefix + "abc");

RegExp(`${prefix}abc`);

new RegExp(String.raw`^\d\. ${suffix}`);

# 选项

此规则有一个对象选项:

  • disallowRedundantWrapping 设置为 true 额外检查不必要的包装正则表达式字面(默认 false)。

# disallowRedundantWrapping

默认情况下,当正则表达式字面不必要地包装在 RegExp 构造函数调用中时,此规则不会检查。When the option disallowRedundantWrapping is set to true, the rule will also disallow such unnecessary patterns.

{ "disallowRedundantWrapping": true }incorrect 代码示例

/*eslint prefer-regex-literals: ["error", {"disallowRedundantWrapping": true}]*/

new RegExp(/abc/);

new RegExp(/abc/, 'u');

{ "disallowRedundantWrapping": true }correct 代码示例

/*eslint prefer-regex-literals: ["error", {"disallowRedundantWrapping": true}]*/

/abc/;

/abc/u;

new RegExp(/abc/, flags);
Last Updated: 5/13/2023, 8:55:38 PM