Skip to main content
Participant
July 16, 2010
Answered

Replacing occurrences of a word by links

  • July 16, 2010
  • 1 reply
  • 1967 views

Hello,

I'm trying to write a Javascript script that would replace every occurrences of a given word in an Indesign CS3 document by a hyperlink pointing to a given URL.

I'm very new to Indesign scripting, and I don't know where to start. I've tried searching this forum, but couldn't find the answer to my problem.

If anyone can help...

Thanks,

Bertrand

This topic has been closed for replies.
Correct answer grefel

You could use my findAndDo Script (blog is in german): http://www.indesignblog.com/?p=7

for a hyperlink you need to change it:

app.changeGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "SEARCH";
var erg = app.activeDocument.findGrep ();     

for (var i = erg.length - 1; i >= 0; i--) {
    var _hlinkSource = app.activeDocument.hyperlinkTextSources.add(erg);
    var _destination = app.activeDocument.hyperlinkURLDestinations.add("http://www.google.de");
    app.activeDocument.hyperlinks.add(_hlinkSource, _destination);
}

1 reply

grefel
Community Expert
grefelCommunity ExpertCorrect answer
Community Expert
July 16, 2010

You could use my findAndDo Script (blog is in german): http://www.indesignblog.com/?p=7

for a hyperlink you need to change it:

app.changeGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "SEARCH";
var erg = app.activeDocument.findGrep ();     

for (var i = erg.length - 1; i >= 0; i--) {
    var _hlinkSource = app.activeDocument.hyperlinkTextSources.add(erg);
    var _destination = app.activeDocument.hyperlinkURLDestinations.add("http://www.google.de");
    app.activeDocument.hyperlinks.add(_hlinkSource, _destination);
}

Participant
July 16, 2010

Thank you very much Grefel! Your script works perfectly and creates hyperlinks for all the occurrences of my word.

However there are two more things I need : I'd like the hyperlink object to be invisible, and the text occurrence to appear in blue.

I figured I could make the links invisible by using the line

app.activeDocument.hyperlinks.add(_hlinkSource, _destination).visible=false;

But I'm not sure how I can make the text turn blue. I suppose I have to use apply some function to erg within the loop, is that right?

Jongware
Community Expert
Community Expert
July 16, 2010

Best is to assign a character style on the links. Make one named "link", and specify your color in there. Then in the script, add this:

erg.appliedCharacterStyle = app.activeDocuments.characterStyles.item("link");