no-regex-spaces

禁止在正则表达式中使用多个空格

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

🔧 Fixable

此规则报告的一些问题可通过 --fix 命令行选项自动修复

正则表达式可能非常复杂且难以理解,这就是为什么让它们尽可能简单以避免错误很重要的原因。使用正则表达式可以做的更容易出错的事情之一是使用多个空格,例如:

¥Regular expressions can be very complex and difficult to understand, which is why it’s important to keep them as simple as possible in order to avoid mistakes. One of the more error-prone things you can do with a regular expression is to use more than one space, such as:

var re = /foo   bar/;

在这个正则表达式中,很难判断要匹配多少个空格。最好只使用一个空格,然后指定需要多少个空格,例如:

¥In this regular expression, it’s very hard to tell how many spaces are intended to be matched. It’s better to use only one space and then specify how many spaces are expected, such as:

var re = /foo {3}bar/;

现在很清楚,三个空格是期望匹配的。

¥Now it is very clear that three spaces are expected to be matched.

规则详情

¥Rule Details

此规则不允许正则表达式字面中有多个空格。

¥This rule disallows multiple spaces in regular expression literals.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-regex-spaces: "error"*/

var re = /foo   bar/;
var re = new RegExp("foo   bar");

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-regex-spaces: "error"*/

var re = /foo {3}bar/;
var re = new RegExp("foo {3}bar");

何时不使用

¥When Not To Use It

如果你想在正则表达式中允许多个空格,那么你可以安全地关闭此规则。

¥If you want to allow multiple spaces in a regular expression, then you can safely turn this rule off.

版本

此规则是在 ESLint v0.4.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号