Formatting Issue with Text Insertion in Google Docs Script

I’m having trouble with text formatting in my Google Docs script. I want to add three parts of text, but only make the middle part italic. Like this: Normal Italic Normal.

I’ve tried using appendText() and insertText(), but can’t get it right. When I add the last part, it ends up italic too.

Here’s a simple example of what I’m trying to do:

function addFormattedText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  var part1 = 'Hello ';
  var part2 = 'world';
  var part3 = '!';
  
  var paragraph = body.appendParagraph(part1);
  var italicPart = paragraph.appendText(part2);
  italicPart.setItalic(true);
  // How do I add part3 without it being italic?
}

Any ideas on how to fix this? I’ve looked at other posts but still can’t figure it out. Thanks for any help!

I’ve wrestled with similar formatting challenges in Google Docs scripts before. One trick that worked for me was using the insertText() method instead of appendText() for the last part. Here’s a slight tweak to your code that might do the trick:

function addFormattedText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  var part1 = 'Hello ';
  var part2 = 'world';
  var part3 = '!';
  
  var paragraph = body.appendParagraph(part1);
  var italicPart = paragraph.appendText(part2);
  italicPart.setItalic(true);
  paragraph.insertText(paragraph.getText().length, part3);
}

This approach inserts the last part at the end of the paragraph, maintaining its normal formatting. It’s a bit of a workaround, but it’s been reliable in my experience. Let me know if this solves your issue!

I encountered a similar issue when working with Google Docs scripts. The key is to use the appendText() method for the final part and then adjust the text style. Here’s how you can modify your code:

function addFormattedText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  var part1 = 'Hello ';
  var part2 = 'world';
  var part3 = '!';
  
  var paragraph = body.appendParagraph(part1);
  var italicPart = paragraph.appendText(part2);
  italicPart.setItalic(true);
  var normalPart = paragraph.appendText(part3);
  normalPart.setItalic(false);
}

This approach ensures that only the middle part remains italic. The setItalic(false) on the last part overrides the inherited style from the previous text. Hope this helps solve your formatting issue!

hey sophia, i’ve run into this before. heres a quick fix:

function addFormattedText() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  
  body.appendParagraph('Hello ')
      .appendText('world').setItalic(true)
      .appendText('!').setItalic(false);
}

this chains the methods together and explicitly sets italic off for the last part. lemme know if it works for you!