如何用mailto替换变量:google doc apps脚本中的链接

时间:2019-05-08 12:59:57

标签: google-apps-script mailto

我正在尝试用文本和mailto:链接替换变量。

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

上面的代码将varEmail替换为适当的“电子邮件”文本,但随后使每个文本块成为mailto:链接。我只需要将“电子邮件”文本作为mailto:链接即可。

1 个答案:

答案 0 :(得分:1)

这有点棘手,因为迭代Google文档中的各个元素有些令人困惑。与电子表格不同,文档的结构不是严格定义的,但是您仍然可以获得某些元素的相对坐标。

以下代码对我有用。通常,将花括号括起来以在视觉上在文档中进行区分是一个好主意。

    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");


    }

结果: enter image description here