Search code examples
javascriptadobe-indesign

Script for applying hyperlinks to text


Being unfamiliar with coding I'm having trouble tweaking the code below. I need to hyperlink the "#" and everything after the "#" until a "space". The digits after the "#" can be variables and there may be as many as five digits.

Sample below:

enter image description here

var doc = app.activeDocument; 

// get URL 

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

app.findGrepPreferences.findWhat = '(?i)(?<=# )(https?|www)\\S+\\>='; 

var mURL = doc.findGrep(); 

// get Texte 

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

app.findGrepPreferences.findWhat = '#'; 

var mSource = doc.findGrep(); 

 

for (var k = 0; k <mSource.length; k++){ 

   var mHyperlinkDestination = doc.hyperlinkURLDestinations.add(mURL[k].contents); 

   var mHyperlinkTextSource = doc.hyperlinkTextSources.add(mSource[k]); 

  mHyperlink = doc.hyperlinks.add(mHyperlinkTextSource,mHyperlinkDestination); 

  mHyperlink.name =mURL[k].contents; 

  mHyperlink.visible=false; 

} 

//remove URL text 

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

app.findGrepPreferences.findWhat = '(?i)(?<=# )(https?|www)\\S+\\>='; 

app.changeGrepPreferences.changeTo = ''; 

doc.changeGrep(); 


Solution

  • This should work:

    var doc = app.activeDocument; 
    
    // get URL 
    app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; 
    app.findGrepPreferences.findWhat = '\\s(https?|www)(://).+$'; 
    var mURL = doc.findGrep(); 
    
    // get Texte 
    app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; 
    app.findGrepPreferences.findWhat = '#\\d{1,5}'; 
    var mSource = doc.findGrep(); 
    
    for (var k = 0; k <mSource.length; k++){ 
      var mHyperlinkDestination = doc.hyperlinkURLDestinations.add(mURL[k].contents); 
      var mHyperlinkTextSource = doc.hyperlinkTextSources.add(mSource[k]); 
      mHyperlink = doc.hyperlinks.add(mHyperlinkTextSource,mHyperlinkDestination); 
      mHyperlink.name =mURL[k].contents + '_' + k; 
      mHyperlink.visible=false; 
    } 
    
    //remove URL text 
    app.findGrepPreferences = app.changeGrepPreferences = NothingEnum.nothing; 
    app.findGrepPreferences.findWhat = '(?<= )(https?|www)(://).+$'; 
    app.changeGrepPreferences.changeTo = ''; 
    doc.changeGrep(); 
    

    Overall it, was just some minor tweaks

    1) Change the grep search for the URLs

    2) Changed the grep search for the numbers ("#" followed by 1-5 digits)

    3) Two hyperlinks cannot have the same name. I changed that line to also number them, you may want to tweak to suit your needs, one thing you could do is use mSource[k].contents + '_' + mURL[k].contents, though if you have repeats, you'll run into the same problem.