Google Apps Script Make text a clickable URL using replaceText()

12,202

Here is how it goes, at least if you have only one occurrence of the url placeHolder.

If you have more than one then you should iterate the whole doc content to find each or them and replace them all.

function myFunction() {
  var url = 'http://www.google.com';
  var doc = DocumentApp.getActiveDocument();// or DocumentApp.openById(file.getId()); as in your example code
  var element = doc.getBody().findText("<<urlGoesHere>>");
  if(element){ // if found a match
    var start = element.getStartOffset();
    var text = element.getElement().asText();
    text.replaceText("<<urlGoesHere>>",url);
    text.setLinkUrl(start, start+url.length, url);
    doc.saveAndClose();
  } // else do nothing
}
Share:
12,202
Employee
Author by

Employee

Updated on June 30, 2022

Comments

  • Employee
    Employee almost 2 years

    I have this code that opens the file and replaces a string using replaceText.

    var url = 'http://www.test.com';
    var doc = DocumentApp.openById(file.getId());
    doc.replaceText("<<urlGoesHere>>", url);
    doc.saveAndClose();
    

    When I open the doc, the replacement has occured, but the url is not a clickable hyperlink, it's just static text. Is there a way to programmatically make it a clickable link?

    I found this method of text called setLinkUrl, but there's no documentation/examples: https://developers.google.com/apps-script/reference/document/text#setLinkUrl(String)

    Any ideas?

  • Employee
    Employee over 10 years
    This works, thanks! I don't have enough reputation to upvote. Also, as usual, thanks for your contributions to the Google Apps Script community. I often find answers to many of my problems in your responses.