如何使用谷歌应用程序脚本在谷歌文档的指定位置插入文本



我有一个包含文本的文档。我想找到单词(li(并通过添加新行插入新单词。我找到了下面的脚本,可以找到文本:

matchPosition = theDoc.getBody().findText("put stuff here").getStartOffset();
theDoc.getBody().editAsText().insertText(matchPosition, "The new stuff");

但这并不能正常工作,因为它给出了单词从起始行的位置,当我们插入新文本时,它计算的是从文档开始的位置,而不是从该行开始的位置。希望你能理解我的意思。

总之,有没有什么方法可以让我们在文档中的任何地方找到单词的第一个出现,并在找到的单词的下一行添加一个新词?

我刚刚找到了一种在指定位置插入文本的方法:

for (var i = 0; i < paragraphs.length; i++) {
var text = paragraphs[i].getText();

if (text.includes("a href")==true) 

{
body.insertParagraph(i, "Test Here")
}
}

这将遍历所有段落的文本,当它找到匹配的单词时,它会在指定的位置添加一个新段落,您可以在该位置添加所需的单词。

您可以在文档中搜索指定的文本并执行不同的操作。

可以添加具有n特征符的新行。

替换文本:

function insert_text_after_pattern() {
// get the document's body
var body = DocumentApp.getActiveDocument().getBody();
// the patten to find in the text
var pattern = "my pattern" // you can use Regular Expressions
// the text to insert
var str = "[new text]"
// Replace the text
body.replaceText(pattern, pattern + str);
}

将文本附加到段落中,匹配样式:

function insert_text_after_pattern() {
// get the document's body
var body = DocumentApp.getActiveDocument().getBody();
// the patten to find in the text
var pattern = "my pattern" // you can use Regular Expressions
// the text to insert
var str = "[new text]"
// find the position where to insert the text
var matchPosition = body.findText(pattern);
// get the text element at position
var textElement = matchPosition.getElement();
// append text
textElement.appendText(str);

用自己的风格将文本附加到段落中:

function insert_text_after_pattern() {
// get the document's body
var body = DocumentApp.getActiveDocument().getBody();
// the patten to find in the text
var pattern = "my pattern" // you can use Regular Expressions
// the text to insert
var str = "[new text]"
// find the position where to insert the text
var matchPosition = body.findText(pattern);
// get the text element at position
var textElement = matchPosition.getElement();
// get its parent (paragraph)
var parent = textElement.getParent();
// append text to paragraph
var newText = parent.appendText(str);
// set style
newText.setBold(true);
}

最新更新