如何用 mailto 替换变量:link in google doc apps 脚本
how to replace variable with mailto: link in google doc apps script
我正在尝试用文本和邮箱替换变量:link。
copyBody.replaceText('varEmail', email).setLinkUrl('mailto:'+email);
以上代码将 varEmail
替换为适当的 'email' 文本,但随后它使每个文本块成为一个 mailto:link。我只需要 'email' 文本作为 mailto:link.
这有点棘手,因为遍历 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");
}
结果:
我正在尝试用文本和邮箱替换变量:link。
copyBody.replaceText('varEmail', email).setLinkUrl('mailto:'+email);
以上代码将 varEmail
替换为适当的 'email' 文本,但随后它使每个文本块成为一个 mailto:link。我只需要 'email' 文本作为 mailto:link.
这有点棘手,因为遍历 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");
}
结果: