Kong Hantrakool
Kong Hantrakool

Reputation: 1865

Google App Script replaceText to replace only first occurrence of matched string

I would like to use google appscript to replace text on my google doc to convert it to PDF. But the problem is the function replaceText(textToReplace, newText); just remove every occurrence of the matched text. I just want to remove only the first occurrence. How to do that?

Upvotes: 5

Views: 2258

Answers (1)

user6655984
user6655984

Reputation:

The replaceText method can be limited in scope to an element, by calling it on that element. But that does not help if the first paragraph where the text is found contains multiple instances of it: they are all going to be replaced.

Instead, use findText to find the first match, and then call deleteText and insertText to execute replacement.

// replaces the first occurrence of old
function replaceFirst(old, replacement) {    
  var body = DocumentApp.getActiveDocument().getBody();
  var found = body.findText(old);
  if (found) {
    var start = found.getStartOffset();
    var end = found.getEndOffsetInclusive();
    var text = found.getElement().asText();
    text.deleteText(start, end);
    text.insertText(start, replacement);
  }
}

If you think this ought to be easier, you are not alone.

Upvotes: 6

Related Questions