Iván Renison
Iván Renison

Reputation: 51

Format keywords in google docs with google apps script

i'm trying to make a google app script for google docs that puts all the occurrences of a string in a document in bold style, for example, for this text:

hello

hello

good by

000000000000000000 hello 00000

Hello hello hello

000000000000000001111111111111111111111111222222222222222222222233333333333333333444444444444444444444445555555555555 hello

If the string is hello, I would like the script to put it like this:

hello

hello

good by

000000000000000000 hello 00000

Hello hello hello

000000000000000001111111111111111111111111222222222222222222222233333333333333333444444444444444444444445555555555555 hello

I made this code:

  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  var Style = {};
  Style[DocumentApp.Attribute.BOLD] = true;

  var found = body.findText("hola");

  while(found != null) {
    found.getElement().setAttributes(Style);
    found = body.findText("hello", found);
  }

But what I obtain after running the code, is this:

hello

hello

good by

000000000000000000 hello 00000

Hello hello hello

000000000000000001111111111111111111111111222222222222222222222233333333333333333444444444444444444444445555555555555 hello

So the code puts in bold all the line that contains the string hello, and not only the string hello

Somebody knows how could I do to put in bold only the string hello and not all the line that contains hello?

Upvotes: 0

Views: 153

Answers (1)

Jason E.
Jason E.

Reputation: 1221

You need to specify the start and end of the text you are trying to edit by using getStartOffset() and getEndOffsetInclusive(). This will prevent your script to format the entire text block to bold. Please see below code:

function myFunction() {
  var document = DocumentApp.getActiveDocument();
  var body = document.getBody();

  var Style = {};
  Style[DocumentApp.Attribute.BOLD] = true;

  var found = body.findText("hello");

  while(found != null) {
    var foundText = found.getElement().asText();
    var start = found.getStartOffset();
    var end = found.getEndOffsetInclusive();
    foundText.setAttributes(start, end, Style)
    found = body.findText("hello", found);
  }
}

Running this resulted to this: enter image description here

Upvotes: 0

Related Questions