Use Google Apps Script to apply heading style to a

2019-04-12 21:51发布

问题:

I am using Google App Scripts in a Google Doc, how do you write a function to find all instances of a word and apply a heading style to it:

For example, I want every instance of "Dogs"...

  • Cats
  • Dogs
  • Fish

and style "dogs" with "Heading 2" so it looks like:

  • Cats
  • Dogs

  • Fish

Using Find in App Scripts on Sheets is everywhere online, but there are not many examples of using App Scripts in Docs. Sheets does not have the option to reformat text as Headings, so there are no examples of it.

回答1:

The methods to use are:

  • findText, applied to document Body. It finds the first match; subsequent matches are found by passing the previous match as the second parameter "from". The search pattern is a regular expression presented as a string, in this example (?i)\\bdogs\\b where (?i) means case-insensitive search, and \\b is escaping for \b, meaning word boundary — so we don't restyle "hotdogs" along with "dogs".
  • getElement, applied to RangeElement returned by findText. The point is, the matching text could be only a part of the element, and this part is called RangeElement. We can't apply heading style to only a part, so the entire element is obtained.
  • getParent, applied to the Text element returned by getElement. Again, this is because heading style applies at a level above Text.
  • setAttributes with the proper style (an object created in advance, using appropriate enums). This is applied to the parent of Text, whatever it happened to be - a paragraph, a bullet item, etc. One may wish to be more selective about this, and check the type of the element first, but I don't do that here.

Example:

function dogs() {
  var body = DocumentApp.getActiveDocument().getBody();
  var style = {};
  style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING2;
  var pattern = "(?i)\\bdogs\\b";

  var found = body.findText(pattern);
  while (found) {
    found.getElement().getParent().setAttributes(style);
    found = body.findText(pattern, found);
  }
}