javascript Javascript正则表达式创建错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8095658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:15:34  来源:igfitidea点击:

Javascript regexp creation error

javascriptregex

提问by Dmitry Belaventsev

I have the following JavaScript code:

我有以下 JavaScript 代码:

aw_check_custom_validation['my-phone'] = /^\+[0-9]{1,3}(\s[0-9]{1,6}\s|\([0-9]{1,6}\)|[0-9]{1,6})[0-9\s]{5,8}$/u;

and I receive the following error:

我收到以下错误:

Uncaught SyntaxError: Invalid flags supplied to RegExp constructor 'u'

Why the /u flag causes this error?

为什么 /u 标志会导致此错误?

回答by Tim Pietzcker

Well, the /uflag is PHP-specific, enabling Unicode support (which your regex isn't using anyway, unless you're planning on matching Unicode whitespace characters with the \sshorthand). Why not just remove it?

好吧,该/u标志是特定于PHP 的,启用 Unicode 支持(您的正则表达式无论如何都不会使用,除非您计划将 Unicode 空白字符与\s速记匹配)。为什么不直接删除它?

For reference, JavaScript only supportsthe /g(global matching), /i(case-insensitive matching) and /m(multiline, i. e. allow ^and $to match at the start and end of each line) modifiers.

作为参考,JavaScript的仅支持/g(全局匹配), /i(不区分大小写匹配)和/m(多行,即,允许^$匹配在启动和每一行的端部)改性剂。

回答by Matt

It's a highlycryptic message that means that the uflag you are passing to the RegEx constructor is invalid. JavaScript supports;

这是一个非常神秘的消息,这意味着u您传递给 RegEx 构造函数的标志无效。JavaScript 支持;

  • g(global match)
  • m("Treat beginning and end characters (^ and $) as working over multiple lines")
  • i(case insensitive match)
  • g(全局匹配)
  • m(“将开始和结束字符(^ 和 $)视为在多行上工作”)
  • i(不区分大小写匹配)

For further info, see the MDC documentation

有关更多信息,请参阅 MDC 文档

回答by Green

Not sure if it is your case or not, but I had similar issue with Node.js:

不确定是否是您的情况,但我对 Node.js 有类似的问题:

SyntaxError: Invalid flags supplied to RegExp constructor 'u'

SyntaxError: 提供给 RegExp 构造函数 'u' 的标志无效

I fixed it simply by updating Node.js in my Ubuntu server. Previous version was:

我只是通过在我的 Ubuntu 服务器中更新 Node.js 来修复它。以前的版本是:

$ node -v
v5.1.1

Then I did:

然后我做了:

$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
   ... long output
$ sudo apt-get install -y nodejs
   ... shorter output
$ node -v
v6.7.0

And no more issues.

没有更多的问题。

回答by Dave Newton

Because it's not a valid JavaScript regex flag; the valid flags are g(global), i(ignore case), and m(multiline).

因为它不是有效的 JavaScript 正则表达式标志;有效标志为g(全局)、i(忽略大小写)和m(多行)。