Regarding the second part of your question, coupled with the fact that you are starting your counter from 0, the first pass of the loop will record 0 occurrence instead of 1.
What you can do to fix that and also keep it in one line:
value.replace("__increment__", util.counter++)
i.e. Increment the counter inline.
In fact ++util.counter
would be better. And remove the next line of util.counter += 1
.
How you can better your algorithm is beyond me!