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

我是研究僧i 提交于 2019-12-09 18:52:59

问题


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


来源:https://stackoverflow.com/questions/46675577/use-google-apps-script-to-apply-heading-style-to-all-instances-of-a-word

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