I want to get the second “.at”‘index in “cat, bat, sat, fat”, the program is:
var text = "cat, bat, sat, fat";
var pattern = /.at/g;
var matches = pattern.exec(text);
var num = 2;
var i = 0;
while(pattern.test(text)){
if(++i == num){
alert(matches.index);
break;
}
matches = pattern.exec(text);
}
The right index should be 5, but why I get 10, please?
-_-
Your problem is because you’re using the same regex for both
.test()and.exec()and expecting the state to not be affected, butlastIndexis advanced by the.test()so it’s not correct when the next.exec()happens. To eliminate that issue, you can remove the.test()and then it works (and is more efficient):Working demo here: http://jsfiddle.net/jfriend00/rbWQj/