Home > InDesign Scripts > Find colored words

Find colored words

Let’s say you have script and you need to create loop, but, loop count depends on special color word count. Here is little snippet for counting words in color of your choice.

app.findGrepPreferences = NothingEnum.nothing;
app.changeGrepPreferences = NothingEnum.nothing;

app.findGrepPreferences.findWhat = "\\w{2,}";
app.findGrepPreferences.fillColor = "MyColor";

var result = Number(app.activeDocument.findGrep().length);


So, this returns number of occurrences in document.

First two lines just clear GREP search preferences. Next, we set GREP search string, because of double-escaping we need to input double backslash instead of one, then, ‘w’ stands for ‘Any Word Character’, and we set the minimal length of word to prevent picking up single letters with ‘{}’. If you want more info about InDesign GREP, I suggest you buying Peter Kahrels book ‘GREP in InDesign CS3/CS4‘. Then we have to set fillColor property for search. You can type your color swatch name, or you can build swatch selector. In next post we will take a look how to do it.

If you want to search just selected frame alter line 6 like this:

var result = Number(app.selection[0].findGrep().length);

If you have more than one selected text frames and they are not threaded, you need to loop through selection and do individual search for each frame. Don’t forget to check constructor of selected elements! If you do it in loop you can do it like this:

if(app.selection[i] instanceof TextFrame){
    //do search

If you have threaded frames, alter line 6 like this:

var result = Number(app.selection[0].parentStory.findGrep().length);

Now we select parentStory and then do GREP search, so we get results from all threaded frames.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: