Why is fasle above and true
below?var re = null ,result ,i;
for (i=0; i < 10; i++){
re = new RegExp("cat", "g");
re.test("catastrophe");
console.log(re.test("catastrophe")); //false
result = re.test("catastrophe");
console.log(result); //true
}
The following excerpts are from http://www.w3school.com.cn/js...
JavaScript lastIndex property
JavaScript RegExp object
Definition and usage
The lastIndex property is used to specify the starting position of the next match.
Syntax
RegExpObject.lastIndex
Description
This attribute stores an integer, which declares the position of the first character after the last matched text.
The last matching result is found by the methods RegExp.exec() and RegExp.test(), both of which use the position pointed by the lastIndex attribute as the starting point for the next retrieval. In this way, you can iterate through all matching text in a string by calling these two methods repeatedly.
This property is readable and writable. It can be set whenever the next search for the target string starts. When the methods exec() or test() can no longer find matching text, they automatically reset the lastIndex property to 0.
Tips and Notes
Important: RegExp objects that do not have the g flag and do not represent a global mode cannot use the lastIndex property.
Tips: If you start to retrieve another new string after successfully matching a certain string, you need to manually set this property to 0.
You can take a look here, http://www.dewen.net.cn/q/468/
Because the global matching mark g is used in the regular expression, the regular expression will record the successful matching position lastIndex, and continue matching from this Position matches backward.
So when matching for the second time, there is no need to look at the previous cat, just remove the g.