use*_*207 7 google-apps-script
我想在Google文档中找到一个单词的所有实例并突出显示它们(或评论 - 任何事情都如此突出).我创建了以下函数,但它只找到了单词的第一个外观(在本例中为"the").任何关于如何找到该单词的所有实例的想法将不胜感激!
function findWordsAndHighlight() {
var doc = DocumentApp.openById(Id);
var text = doc.editAsText();
//find word "the"
var result = text.findText("the");
//change background color to yellow
result.getElement().asText().setBackgroundColor(result.getStartOffset(), result.getEndOffsetInclusive(), "#FFFF00");
};
Run Code Online (Sandbox Code Playgroud)
小智 11
我知道这是一个老人,但这是我在Google Script中为文本添加效果的方法.下面的示例专门用于为文档中特定字符串的所有匹配项添加突出显示.
function highlightText(findMe) {
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText(findMe);
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the Element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Change the background color to yellow
foundText.setBackgroundColor(start, end, "#FCFC00");
// Find the next match
foundElement = body.findText(findMe, foundElement);
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,简单的 javascript 就足够了,
var search = searchtext;
var index = -1;
while(true)
{
index = text.indexOf(search,index+1);
if(index == -1)
break;
else
/** do the required operation **/
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
14277 次 |
| 最近记录: |