Chapter 2. The Basics

Regular expressions are used in string methods, so they work on literal text. This has certain implications for their use in InDesign JavaScripts aimed at formatted documents. When you do an "ordinary" search in JavaScript, the search( ) method is applied to an InDesign object, so you would write statements such as myStory.search( 'Lara', true, true ) to search for the string "Lara" in the story referenced by myStory. Using a regular expression, however, you need to write myStory.contents.match(. . .) to search the contents of the same story (with an appropriate regex in place of . . .).

Regular expressions are written between slashes (/), and these slashes are what tell string functions such as match( ), replace( ), and split( ) that they should interpret their argument as a regex. In all other respects, you search a string using a regex just as you would use any other string function. For instance, to find all instances of the word pound in a text string, you would use these lines:

myString = 'A pound of venison in weight is eight pounds in money.';
myPounds = myString.match( /pounds?/g );

As you can see, the match( ) function is used like other JavaScript functions. The regular expression used here is /pounds?/. The question mark indicates that the preceding character is optional, which is to say that we want to match both pound and pounds. Any character entered between the slashes is part of the regular expression, so don't type spaces as these will ...

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.