6.2. Replace Selectively

Suppose you're working on a book in which the author has used Diagram in the figure captions, and also uses it to refer to the figures. The book's publisher wants to use Figure instead of Diagram, so now you have to do the replacement, but, naturally, only if Diagram is followed by a digit. To cater for plural forms as well (Diagrams 3 and 4) we make the s optional by adding a question mark. Here is the script:

var myMatch = documentContents( app.activeDocument ).match( /Diagrams? \d/g );
if( myMatch != null )
     {
     app.findPreferences = app.changePreferences = null;
     for( var i = 0; i < myMatch.length; i++ )
          app.activeDocument.search( myMatch[i], false, true,
              myMatch[i].replace( 'Diagram', 'Figure' ) );
     }

The last line in the script derives the replacement form from the search form simply by replacing Diagram with Figure; the following space and digit remain in place. A simple replacement suffices in this case, but sometimes a regex is necessary here as well. This is shown in the next example.

Get Automating InDesign with Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.