使用构造函数创建的正则表达式不适用于 Safari [英] Regex created with constructor not working with Safari

查看:111
本文介绍了使用构造函数创建的正则表达式不适用于 Safari的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据记载,可以使用 2 种方法创建正则表达式:

It is documented that one can create regex expressions using 2 methods:

1.简单表达

   /ab+c/i;

2.使用构造函数

  new RegExp(/ab+c/, 'i');
  new RegExp('ab+c', 'i');

我使用了在 Chrome、Mozilla 中通过但在 Safari 中未通过的 RegExp(/ab+c/, 'i') 版本,返回错误:

I have used the version RegExp(/ab+c/, 'i') which passed in Chrome, Mozilla but not in Safari, returning an error:

cannot supply flags when constructing one regexp from another

我已改用第一种方法,现在可以使用了,但有两件事我不清楚:

I have switched to the first method and it works now but there are 2 things that are not clear for me:

  1. '/' 字符在这样的表达式中代表什么.我已经看到它在在线正则表达式测试站点中默认添加

  1. what does '/' character stand for in an expression like that. I've seen it added by default in online regex test sites

为什么 safari 无法与我使用的版本一起使用

why safari failed to work with the version that i used

推荐答案

正则表达式构造函数符号 (new RegExp(...)) 主要用于需要向模式传递变量时.如果模式是硬编码",请立即使用正则表达式文字:var reg =/ab+c/i.请参阅更多关于何时使用哪种表示法这里.

The regex constructor notation (new RegExp(...)) is mainly used when you need to pass a variable to your pattern. If the pattern is "hard-coded", use a regex literal straight away: var reg = /ab+c/i. See more on when to use which notation here.

Safari 目前不接受正则表达式文本作为 RegExp 构造函数的第一个参数,其他一些浏览器也不接受.因此,将常规字符串模式作为第一个参数传递更安全.

Safari currently does not accept a regex literal as the first argument to the RegExp constructor, nor do some other browsers. Thus, it is safer to pass a regular string pattern as the first argument.

至于 /.../,这些是正则表达式分隔符,用于分隔 action/pattern/modifiers.在 JS 中,不使用 action 部分,修饰符仅限于 i(不区分大小写)、g(全局匹配)和m(多行模式重新定义 ^$ 行为,以便它们可以匹配行的开始/结束而不是开始/结束一个字符串).

As for the /.../, these are regex delimiters that delimit action/pattern/modifiers. In JS, the action part is not used, and the modifiers are limited to i (case-insensitive), g (global matching) and m (multiline mode to redefine the ^ and $ behavior so that they could match the start/end of a line instead of the start/end of a string).

这篇关于使用构造函数创建的正则表达式不适用于 Safari的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆