The above code makes usage of the fact, that .replace() can take a funarg (functional argument) as second parameter. That callback is passed in the current match of the matched regexp pattern and the index from that match (along with some others which we are not interested in here). Now that is all information we need to accomplish your desired result. We write a little function wish takes three arguments:

Sorry, I added a bad example, i need to modify my match like that — before: im_1_2_3_4, after im_1_%2%_3_4. Function still the same, detect all numbers in string and replace match with my index.
–
ruslan.savenokJul 27 '11 at 11:45