解决方法
A regular expression literal is an
input element that is converted to a
RegExp object (section 15.10) when it
is scanned. The object is created
before evaluation of the containing
program or function begins. Evaluation
of the literal produces a reference to
that object; it does not create a new
object.
该规范中的错误已在ES4中得到确认:
In ES3 a regular expression literal
like /ab/mg denotes a single unique
RegExp object that is created the
first time the literal is encountered
during evaluation. In ES4 a new
RegExp object is created every time
the literal is encountered during
evaluation.
实现因浏览器而异. Safari和IE按照ES4处理文字,但Firefox和Chrome似乎按照ES3对待它们.
在各种浏览器中尝试以下代码,你会明白我的意思:
function f() { return /abc/g.test('abc'); } alert(f()); // Alerts true alert(f()); // Alerts false in FF/Chrome
和….相比:
function f() { return RegExp('abc','g').test('abc'); } alert(f()); // Alerts true alert(f()); // Alerts true
注意,false会被警告,因为该函数仍在使用该函数的上一次调用的正则表达式,其lastIndex已更新,这意味着它将不再匹配字符串“abc”.
提示:实例化RegExp不需要new运算符. RegExp()本身的工作方式相同……
有关ES3 / 4问题的更多信息:Regex/lastIndex – Unexpected behaviour