2 Replies Latest reply on Feb 24, 2012 9:50 AM by secondgradersrule

    Javascript replace text in selection

    secondgradersrule Level 1

      I know this is simple, but I can't seem to find/replace text in a variable that contains a portion (one line) of text that has been selected in an InDesign document.

      Here is the code fragment:


      myLine = app.activeDocument.selection[0].paragraphs[iLoop].contents; 

      myLine = myLine.replace("<","");

      myLine = myLine.replace("=","\t");


      I 'alert' the value of myLine after the code executes and the wedge and = characters are still there.


      Thanks in advance for any help.

        • 1. Re: Javascript replace text in selection
          absqua Level 4

          myLine is, in your snippet, a JavaScript string. You manipulate it in JavaScript but never plug it back into your InDesign text object. You need to do something like:


          myLine = app.activeDocument.selection[0].paragraphs[iLoop];
          myLine.contents = myLine.contents.replace("<", "").replace("=", "\t");


          Note that replace() as you're using it will only replace the first instance of the character it finds. To replace them all you need to feed it a RegExp object with a global flag as the first argument:


          myLine.contents = myLine.contents.replace(/</g, "").replace(/\=/g, "\t");



          • 2. Re: Javascript replace text in selection
            secondgradersrule Level 1

            Had I been paying attention, I would have noticed that my code was, in fact, replacing the first instance of the characters in the line.  A bonehead move, but I am afraid of RegExp anyway. 


            The code does go on to place the modified myLine back  the contents of the selection, and then apply the appropriate paragraph style. 


            Thanks for the quick help.


            Dick Conrad