Chapter 5. Working with Plain Text

Now that we can find things, let us turn to replacing text. In this section we confine ourselves to replacing text in defined text strings. In the next section, we deal with replacing text in unformatted and formatted InDesign documents.

You replace text using the JavaScript string method replace( ), which takes two arguments. In its simplest form, replace can be used to replace literal text, as follows:

myString = 'one two three four five six';
myString.replace( ' ', '_' );

This replaces the first space in myString with underscore character. To replace all spaces with an underscore, use a regular expression in place of the first argument:

myString = 'one two three four five six';
myString.replace( / /g, '_' );

The regular expression here is as simple as they get: "match spaces, globally," in other words, "match all spaces." Spaces are a bit tricky: they're not always easy to spot in regexes, so you could use the hex code for the space and write the regex as /\x20/ for clarity. Replace takes any of the regexes that we saw earlier.

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.