Search code examples
google-apps-scriptgoogle-sheetsreplacefull-text-searchgoogle-docs

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


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?


Solution

  • 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.