Home > OS >  How to insert text at specified position in google doc using google apps script?
How to insert text at specified position in google doc using google apps script?

Time:12-03

I have document which contains the text. I want to find the word (li) and insert new word by adding new line. I have found the following script that finds the text:

matchPosition = theDoc.getBody().findText("put stuff here").getStartOffset();
theDoc.getBody().editAsText().insertText(matchPosition, "The new stuff");

But this does not work properly because it gives the position of word from the starting line and when we insert a new text it counts position from the start of the document instead of the start of that line. Hope you understand what I am saying.

So to summarize, Is there any way from which we can find the first occurrence of the word anywhere in the document and add a new word on the next line of the found word?

CodePudding user response:

I just found a way to insert text at a specified position:

for (var i = 0; i < paragraphs.length; i  ) {
    var text = paragraphs[i].getText();
        
    if (text.includes("a href")==true) 
    
    {
      body.insertParagraph(i, "Test Here")
     }
 }

This loops through all the paragraphs' text and when it finds the matching word, it adds a new paragraph at the specified position in which you can add your desired word.

  • Related