Search code examples
google-apps-scriptmailto

how to replace variable with mailto: link in google doc apps script


I am trying to replace a variable with text and a mailto: link.

copyBody.replaceText('varEmail', email).setLinkUrl('mailto:'+email);

The above code replaces the varEmail with the appropriate 'email' text but then it makes every text block a mailto: link. I just need the 'email' text to be the mailto: link.


Solution

  • It's a bit tricky as iterating over individual elements inside a Google doc is somewhat confusing. Unlike spreadsheets, the structure of a doc isn't as rigidly defined but you can still get relative coordinates for some elements.

    The following code worked for me. As a rule, it might be a good idea to surround patterns with curly braces to distinguish them visually in the doc.

        function addUrl(){   
    
        //Placeholder patterns
         var pattern = "{{mailTo}}";
         var replacement = "mailto: antond@example.com";
    
        //Open the bound doc
        var doc = DocumentApp.getActiveDocument();
    
        //Get body
        var body = doc.getBody();
    
        //find rangeElement
        var rangeElement =  body.findText(pattern);
    
        //if the element is partial, check how far it is from the start of the range
        var startOffset = rangeElement.getStartOffset();
    
        //... and from the end.
        var endOffset = rangeElement.getEndOffsetInclusive();
    
        //Get the full Element from the partial RangeElement and cast it to Text
        var text = rangeElement.getElement().asText();
    
          //If element is partial, pick only the part that matches the pattern.
          //Add the URL first to avoid the link not being added to the entire pattern later.
        if (rangeElement.isPartial()) {
    
            text.setLinkUrl(startOffset, endOffset, replacement);
    
        } else {
    
             text.setLinkUrl(replacement);
          }
    
          text.replaceText(pattern, "Anton Dementiev");
    
    
        }
    

    Result: enter image description here