Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...