Skip to main content
February 24, 2012
Answered

Javascript replace text in selection

  • February 24, 2012
  • 2 replies
  • 6442 views

I know this is simple, but I can't seem to find/replace text in a variable that contains a portion (one line) of text that has been selected in an InDesign document.

Here is the code fragment:

myLine = app.activeDocument.selection[0].paragraphs[iLoop].contents; 

myLine = myLine.replace("<","");

myLine = myLine.replace("=","\t");

I 'alert' the value of myLine after the code executes and the wedge and = characters are still there.

Thanks in advance for any help.

This topic has been closed for replies.
Correct answer absqua

myLine is, in your snippet, a JavaScript string. You manipulate it in JavaScript but never plug it back into your InDesign text object. You need to do something like:

myLine = app.activeDocument.selection[0].paragraphs[iLoop];

myLine.contents = myLine.contents.replace("<", "").replace("=", "\t");

Note that replace() as you're using it will only replace the first instance of the character it finds. To replace them all you need to feed it a RegExp object with a global flag as the first argument:

myLine.contents = myLine.contents.replace(/</g, "").replace(/\=/g, "\t");

Jeff

2 replies

February 24, 2012

Had I been paying attention, I would have noticed that my code was, in fact, replacing the first instance of the characters in the line.  A bonehead move, but I am afraid of RegExp anyway. 

The code does go on to place the modified myLine back  the contents of the selection, and then apply the appropriate paragraph style. 

Thanks for the quick help.

Dick Conrad

absquaCorrect answer
Inspiring
February 24, 2012

myLine is, in your snippet, a JavaScript string. You manipulate it in JavaScript but never plug it back into your InDesign text object. You need to do something like:

myLine = app.activeDocument.selection[0].paragraphs[iLoop];

myLine.contents = myLine.contents.replace("<", "").replace("=", "\t");

Note that replace() as you're using it will only replace the first instance of the character it finds. To replace them all you need to feed it a RegExp object with a global flag as the first argument:

myLine.contents = myLine.contents.replace(/</g, "").replace(/\=/g, "\t");

Jeff