2 Replies Latest reply on Sep 26, 2018 5:09 AM by jjrger

    Character index in Grep change loop

    jjrger Level 1



      I have to know characters position in a find/change grep loop, and got a problem :


      I use the text "AB", I find each character and add "1".

      The result expected is : "A1B1".

      Unfortunately, with this code, the result is "A11B".


      app.findGrepPreferences.findWhat = ".";  
      myFoundItems = app.activeDocument.findGrep(); 
      for (i = 0; i <myFoundItems.length; i++) { 
           myFoundItems[i].insertionPoints[-1].contents = "1"; 


      I understand the character index is not updated in the loop.

      I don't use changeGrep, because I will need to add many variable contents and formating step by step in each loop.


      Is there a way/a command to get the insertion point index, relative to the new parent content?


      Thanks for your help!

        • 1. Re: Character index in Grep change loop
          [Jongware] Most Valuable Participant

          The problem is that the insertion point indexes of all text changes as soon as you add your first character. The existing list of 'myFoundItems' then is no longer valid.


          The best way to tackle this is to add your characters from last to first. You can reverse your loop to


          for (i = myFoundItems.length-1;i >=0;  i--) {



          which is the usual way of solving this for InDesign. But in this case, using findGrep, it is even easier as hat is an optional Boolean argument to indicate the result list needs to be in reverse order! So just add this argument to findGrep:


          … findGrep(true)


          and it should work.

          • 2. Re: Character index in Grep change loop
            jjrger Level 1

            Wow… so easy

            Many thanks.