0

I have a google Form, and the responses populate a response google Sheet, which has a google Script function to generate a google Document using a template.

I am trying to get the address entered in the Form (stored in the response Sheet) to become a hyperlink in the generated Doc. I have been using the body.replaceText() to replace all the fields I need in the Doc:

    body.replaceText("{{Date}}", date);

and its working well, but the address field I would like to become a hyperlink.

I have been trying to do it this way:

    body.replaceText("{{Location}}", =HYPERLINK("http://www.google.com/maps/place/'+location+'"));

But that does not become a usable hyperlink, resulting with this in the Doc (please note while it becomes a hyperlink on this page it does not become a hyperlink in Docs):

=HYPERLINK("http://www.google.com/maps/place/myplacenotyours")

I have also tried:

   body.replaceText("{{Location}}", location = HYPERLINK("http://www.google.com/maps/place/"+location+));

But this throws up syntax errors.

I have this var:

     var location = e.values[2];

So perhaps it better to use that to create another var as a hypertext? I am now trying:

     var loclink = 'Hyperlink("http://www.google.com/maps/place/'+location+'","'+location+'")'; 

but that doesnt do it either... I'm now starting to think that one can't insert a hyperlink using replace method?

Sorry for the noob question, but I can't figure this out. Can you help me find a solution and put a var into a hypertext link and put that into the Doc as a link?! Cheers.

1 Answers1

0

Something like this:

function insertLink() {

  var pattern = '{{Location}}';
  var url     = 'https://stackoverflow.com/a/69143679/14265469';
  var text    = 'how to paste a link';

  var doc  = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var next = body.findText(pattern);
  if (!next) return;
  var start = next.getStartOffset();

  body.replaceText(pattern, text);
  body.editAsText().setLinkUrl(start, start+text.length-1, url);

}
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23