Back

If your email is not recognized and you believe it should be, please contact us.

  • You must be logged in to reply to this topic.Login

Loop through findGrep

Tagged: ,

Return to Member Forum

  • Author
    Posts
    • #34493
      Janman
      Member

      Hi all,

      I think I have a fairly simple question, but I am unable to figure out where it goes wrong (due to limited experience with scripting). I would appreciate if anyone could explain to me why the following script lines (with proper references to styles not included here) do not fill the textFrame with every Grepfind, but only the first.

      app.findGrepPreferences = app.changeGrepPreferences = null;
      app.findGrepPreferences.appliedParagraphStyle = parTi;
      app.findGrepPreferences.appliedCharacterStyle = titles;
      var docTitles = myDoc.findGrep();
      for (var a=0; a<docTitles.length; a++){
      var TocTitles = docTitles[a];
      }
      var myPage = myDoc.pages.item(1);
      var frame1 = myPage.textFrames.add();
      frame1.geometricBounds = [78.911, 273.75, 237.987, 360.25];
      frame1.contents = TocTitles.contents;
      //returns only 1st, not all Grepfinds

      Cheers,

      Janman

    • #64588
      Brian Pifer
      Participant

      Because you are not performing a task for each find within the “for” loop. All you’re doing is setting the TocTitles variable inside the loop; after you set it the first time, it immediately moves and assigns that variable to the next find. Then, when you exit the loop, you have TocTitles assigned to just one find. You basically need to be doing all the work in the loop, like so:

      var docTitles = myDoc.findGrep();
      var myPage = myDoc.pages.item(1); //fyi, a shorthand for this call is “myDoc.pages[1];”
      var tocFrame = myPage.textFrames.add();
      tocFrame.geometricBounds = [78.911, 273.75, 237.987, 360.25];

      for ( i = 0; i < docTitles.length; i++ ) {
      var tocTitles = docTitles[a];
      tocFrame.contents += tocTitles.contents + “\r”;
      }

      Or you could forget the for loop entirely, and use the array’s join method to combined all the finds into one big chunk, then add them to the text frame.

      var myFinds = …findGrep();
      var myJoin = myFinds.join(“\r”); //the “\r” puts a return mark between each array entry.
      myFrame.contents = myJoin;

    • #64596
      Janman
      Member

      Great, thank you very much for your insightful explanation Brian!

    • #64621
      Brian Pifer
      Participant

      No problem. I realized my explanation about using Join wouldn’t work, since you’re not working with strings with FindGrep(); rather, they’re an array of Text objects. So yes, you would need to loop through regardless.

Viewing 3 reply threads
  • You must be logged in to reply to this topic.
Forum Ads