Search code examples
javascriptreplacefindadobe-indesign

Change text using a variable in InDesign javascript


I'm trying to find all "#"s on the active page and change them to numbers, ie. 1, 2, 3 . . .

The code below is what I thought would work but it doesn't. Instead, it changes every "#" to a "0".

app.findTextPreferences = app.changeTextPreferences = NothingEnum.NOTHING;
app.findTextPreferences.findWhat = "#";

var finds = app.activeDocument.findText();
if (finds.length > 0) {
   for (var i = 0; i < finds.length; i++)  
   {  
      app.changeTextPreferences.changeTo = "no: " + i;
      app.activeDocument.changeText();
   }  
   else
   {
      alert("Nothing has been found");
   }
}

Solution

  • As ali haydar stated, changeText will apply globally and will break the former findText texts references. What you need is to use the contents property in your loop.

    app.findTextPreferences = app.changeTextPreferences = NothingEnum.NOTHING;
    app.findTextPreferences.findWhat = "#";
    
    var finds = app.activeDocument.findText();
    if (finds.length > 0) 
    {
        for (var i = 0; i < finds.length; i++)  
        {  
          finds[i].contents = "no: " + String(i);
        }  
    }
    else
    {
    alert("Nothing has been found");
    }