语法错误:无效的正则表达式标志 "x"

当正则表达式中的标志包含不属于以下之一的任何标志时,会发生 JavaScript 异常 "无效的正则表达式标志":dgimsuvy

¥The JavaScript exception "invalid regular expression flag" occurs when the flags in a regular expression contain any flag that is not one of: d, g, i, m, s, u, v, or y.

如果表达式包含多个有效标志实例,也可能会引发该错误。

¥It may also be raised if the expression contains more than one instance of a valid flag.

信息

¥Message

SyntaxError: Invalid flags supplied to RegExp constructor 'x' (V8-based)
SyntaxError: Invalid regular expression flags (V8-based)
SyntaxError: invalid regular expression flag x (Firefox)
SyntaxError: Invalid flags supplied to RegExp constructor. (Safari)
SyntaxError: Invalid regular expression: invalid flags (Safari)

错误类型

¥Error type

SyntaxError

什么地方出了错?

¥What went wrong?

正则表达式包含无效标志,或者有效标志已在表达式中使用多次。

¥The regular expression contains invalid flags, or valid flags have been used more than once in the expression.

有效(允许)标志为 dgimsuvy。它们在 正则表达式 > 使用标志进行高级搜索 中有更详细的介绍。

¥The valid (allowed) flags are d, g, i, m, s, u, v, and y. They are introduced in more detail in Regular expressions > Advanced searching with flags.

示例

¥Examples

在由斜杠括起来的模式组成的正则表达式文字中,标志在第二个斜杠之后定义。正则表达式标志可以单独使用,也可以按任何顺序一起使用。此语法显示如何使用正则表达式文字声明标志:

¥In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. Regular expression flags can be used separately or together in any order. This syntax shows how to declare the flags using the regular expression literal:

js
const re = /pattern/flags;

它们也可以在 RegExp 对象的构造函数中定义(第二个参数):

¥They can also be defined in the constructor function of the RegExp object (second parameter):

js
const re = new RegExp("pattern", "flags");

下面是一个示例,显示仅使用正确的标志。

¥Here is an example showing use of only correct flags.

js
/foo/g;
/foo/gims;
/foo/uy;

下面的示例显示了一些无效标志 bar 的使用:

¥Below is an example showing the use of some invalid flags b, a and r:

js
/foo/bar;

// SyntaxError: invalid regular expression flag "b"

下面的代码不正确,因为 Web 不是有效标志。

¥The code below is incorrect, because W, e and b are not valid flags.

js
const obj = {
  url: /docs/Web,
};

// SyntaxError: invalid regular expression flag "W"

包含两个斜杠的表达式被解释为正则表达式文字。最有可能的目的是使用单引号或双引号创建字符串文字,如下所示:

¥An expression containing two slashes is interpreted as a regular expression literal. Most likely the intent was to create a string literal, using single or double quotes as shown below:

js
const obj = {
  url: "/docs/Web",
};

也可以看看

¥See also