Use Google Apps Script to apply heading style to all instances of a word

我的未来我决定 提交于 2019-12-04 14:28:36

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);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!