Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 460
Employee Avatar asked Jan 19 '14 00:01

Employee


People also ask

How do you put a link in a script?

To add a hyperlink in a document use Body. appendParagraph with setLinkUrl, then merge. let doc = DocumentApp. create("My Document"); let body = doc.

How do I open a URL in Google Apps Script?

If you want to 'show' the URL, just change this line like this : var link = app. createAnchor(href, href). setId("link");

How do you concatenate in Appscript?

To concatenate two strings (i.e., to join them together), use the concatenation operator ( + ). Both the concatenation operator and the addition operator have the same symbol + but Apps Script will figure out which operation to perform based on the values being operated on.


1 Answers

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
}
like image 155
Serge insas Avatar answered Sep 30 '22 07:09

Serge insas