SyntaxError: invalid regular expression flag "x" - JavaScript 编辑

The JavaScript exception "invalid regular expression flag" occurs when the flags, defined after the second slash in regular expression literal, are not one of g, i, m, su, or y.

Message

SyntaxError: Syntax error in regular expression (Edge)
SyntaxError: invalid regular expression flag "x" (Firefox)
SyntaxError: Invalid regular expression flags (Chrome)

Error type

SyntaxError

What went wrong?

There are invalid regular expression flags in the code. In a regular expression literal, which consists of a pattern enclosed between slashes, the flags are defined after the second slash. They can also be defined in the constructor function of the RegExp object (second parameter). Regular expression flags can be used separately or together in any order, but there are only six of them in ECMAScript.

To include a flag with the regular expression, use this syntax:

var re = /pattern/flags;

or

var re = new RegExp('pattern', 'flags');
Regular expression flags
Flag Description
g Global search.
i Case-insensitive search.
m Multi-line search.
s Allow . to match newlines (added in ECMAScript 2018)
u Unicode; treat pattern as a sequence of Unicode code points
y Perform a "sticky" search that matches starting at the current position in the target string. See sticky

Examples

There are only six valid regular expression flags.

/foo/bar;

// SyntaxError: invalid regular expression flag "b"

Did you intend to create a regular expression? An expression containing two slashes is interpreted as a regular expression literal.

let obj = {
  url: /docs/Web
};

// SyntaxError: invalid regular expression flag "W"

Or did you mean to create a string instead? Add single or double quotes to create a string literal.

let obj = {
  url: '/docs/Web'
};

Valid regular expression flags

See the table above for the six valid regular expression flags that are allowed in JavaScript.

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

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:152 次

字数:4102

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文