Reputation: 1165
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.
Upvotes: 7
Views: 2802
Reputation:
The methods to use are:
(?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". 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);
}
}
Upvotes: 9