什么!?!?
我尝试在Chrome,Firefox,Safari中进行测试。 使用正则表达式与RegExp构造函数,但无济于事。
为什么会这样?
JS Bin附加演示
var re = /null/g; re.test('null null'); //> true re.test('null null'); //> true re.test('null null'); //> falseWHAT!?!?
I tried testing in Chrome, Firefox, Safari. Used regex with RegExp constructor, but to no avail.
Why is this happening?
JS Bin with additional demo
最满意答案
全局正则表达式(使用g标志的表达式)是特殊的。 如果您多次在同一个字符串上调用它们,它们会搜索连续的匹配项。 由于您的测试字符串恰好包含两个null匹配项,因此第三次调用RegExp#test将返回false (无法找到连续的第三个匹配项)。
要解决此问题,您可以放弃g标志,如下所示:
var re = /null/ console.log(re.test('null null')) //=> true console.log(re.test('null null')) //=> true console.log(re.test('null null')) //=> trueGlobal regular expressions (those using the g flag) are special. If you call them on the same string multiple times, they search for successive matches. Since your test string contains exactly two matches for null, the third call to RegExp#test returns false (a third match in a row cannot be found).
To fix this problem, you can abandon the g flag like so:
var re = /null/ console.log(re.test('null null')) //=> true console.log(re.test('null null')) //=> true console.log(re.test('null null')) //=> true
更多推荐
发布评论