Skip to main content
Known Participant
January 24, 2012
Answered

[JS CS5] Get a reference to a block of text

  • January 24, 2012
  • 2 replies
  • 636 views

There's one basic thing I've never been able to figure out. How do you get a reference to a specific block of text, with indexes that you specify?

For instance, if the following text were the beginning of an InDesign story called "story"

The black cat walks in the hall

and if for some reason you wanted to get a reference to the text object that goes from story.characters[2] to right before story.characters[11] (whose contents would be "e black c", if I'm not mistaken), how would you do that?

(Assume there is only one textStyleRange in this object).

This topic has been closed for replies.
Correct answer Jongware

To grab a range of characters, use itemByRange on the story's Characters property:

story = app.activeDocument.stories[0];

range = story.characters.itemByRange(2,11);

alert ("Story: "+story.contents+"\nRange: "+range.contents+"\nType: "+range.constructor.name+"\nLength: "+range.length);

returns this:

2 replies

Jongware
Community Expert
JongwareCommunity ExpertCorrect answer
Community Expert
January 24, 2012

To grab a range of characters, use itemByRange on the story's Characters property:

story = app.activeDocument.stories[0];

range = story.characters.itemByRange(2,11);

alert ("Story: "+story.contents+"\nRange: "+range.contents+"\nType: "+range.constructor.name+"\nLength: "+range.length);

returns this:

richardh6Author
Known Participant
January 24, 2012

Thank you Jongware, that's great!

I didn't try that because I assumed that collections of characters wouldn't be counted as blocks of text for the purposes of things like searching, but I was wrong. I added this to your example:

(Starting with story.contents == "The black cat walks down the hall.")

var story = app.activeDocument.stories[0];
var range = story.characters.itemByRange(2,11);

app.findTextPreferences = NothingEnum.nothing;

app.changeTextPreferences = NothingEnum.nothing;

app.findTextPreferences.findWhat = "black";

app.changeTextPreferences.changeTo = "white";

range.changeText();

and it totally worked. Turned into "The white cat walks down the hall."

richardh6Author
Known Participant
January 24, 2012

In other words, something analagous to

"The black cat walks in the hall".substring(2,11)

but for Indesign text objects, instead of strings.

I'm sure there's something really simple I'm just not thinking of.