Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

google apps script - Finding text (multiple times) and highlighting

I would like to find all the instances of a word in a Google doc and highlight them (or comment - anything so it stands out). I have created the following function, but it only finds the first appearance of the word ("the" in this case). Any ideas on how to find all instances of the word would be appreciated!

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");
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is an oldie, but here's how I add effects to text in Google Script. The example below is specifically for adding highlighting to all occurrences of a particular string in a document.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...