Question

I'm writing InDesign javascript, that do GREP find / change - actually for now I need only find some text and save to my script variable what grep found in $2 value - everything else for my script I know how to do - so all I need for now is to find out how to get this $2

simple example:

app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "(\\d)+(\\d)";
found = app.activeDocument.findGrep();
...
found[0].contents; // this store entire string with both digits and plus, and I need only $2 value (second digit in this case)
Was it helpful?

Solution

InDesign's JS interface does not do that for you, it only returns the complete match.

Since contents is a simple Javascript string (not native InDesign text anymore), you can use Javascript's own match function:

..
app.findGrepPreferences.findWhat = "(\\d)+(\\d)";
found = app.activeDocument.findGrep();
m = found[0].contents.match (/(\d)+(\d)/);
alert (m.join('\n'));

Be careful not to mix InDesign's GREP syntax with Javascript's. In particular, special characters such as ~< are ID extensions and will fail in JS.


Note that for an input of "2014" this will return

2014
1
4

where the first line is the full match (equal to $0), 1 is $1 and 4 is $2. This is most likely not what you expected. Since you are repeatedly matching "group 1" with the +, each next single digit replaces the last found one (expect for the very last one). You probably meant something like

(\d+)(\d)

which will return

2014
201
4

OTHER TIPS

I know this already has an answer, but I thought I'd mention another approach that I think is useful. One way to do this would be to use lookbehinds and lookaheads so that the thing that is in the second set of parentheses is the entirety of the found string. In your case, you could change your search to

(?<=\\d)\\d(?!\\d)

What this says is "find a digit that is preceded by a digit, and followed by something that isn't a digit. Using this, your found array will only contain whatever the second \d matches (the last digit in a number).

Here's a pretty good explanation of how these work: http://carijansen.com/2013/03/03/positive-lookbehind-grep-for-designers/

One thing to note: you can't use \d+ in the lookbehind (it can't be variable length). That's why I use a lookahead as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top