Seems like `lastMatch` should be updated somewhere in here (either `lastMatch = result[i].index`, which should be `lastMatch--` if I'm understanding the code correctly).