Finding text (multiple times) and highlighting

前端 未结 4 1038
青春惊慌失措
青春惊慌失措 2020-12-03 12:44

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 o

4条回答
  •  有刺的猬
    2020-12-03 13:27

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

提交回复
热议问题