Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting in replaceText()

I've got doc.getBody().replaceText(oldregex,newstring) working fine in a Google Document script at the minute, and was hoping to set some bold/italic on newstring. This looks harder than I thought it would be. Has anyone found a tidy way to do this?

I'm currently thinking I'll need to...

  • Build newtext as a range with rangeBuilder
  • Find oldtext and select it as a range (somehow...)
  • Clear the oldtext range and insert the newtext range at the find location

This seems like a lot of work for something that would be trivial with HTML-like tags. I'm definitely missing something. Would really appreciate any suggestions.

like image 671
Richie Avatar asked Jan 29 '26 09:01

Richie


1 Answers

Since replaceText only changes the plain text content, leaving formatting in place, the goal can be achieved by applying formatting before the replacement. First, findText goes through the text and sets bold to every match; then replaceText performs the replacement.

There are two cases to consider: only a part of text in an element is matched (which is typical) and entire element is matched. The property isPartial of RangeElement class distinguishes between these.

function replaceWithBold(pattern, newString) {
  var body = DocumentApp.getActiveDocument().getBody();
  var found = body.findText(pattern);
  while (found) {
    var elem = found.getElement();
    if (found.isPartial()) {
      var start = found.getStartOffset();
      var end = found.getEndOffsetInclusive();
      elem.setBold(start, end, true);
    }
    else {
      elem.setBold(true);
    }
    found = body.findText(pattern, newString);
  }
  body.replaceText(pattern, newString);
}

This seems like a lot of work for something that would be trivial

This is both correct and typical for working with Google Documents using Apps Script.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!