Using Apps Script to transfer a specific part from one Google Doc to another

Hey everyone! I’m trying to move a chunk of text from one Google Doc to another using Apps Script. I’ve got a script that can copy a whole document, but now I need to grab just a part of it. The tricky bit is figuring out how to select the right section.

Here’s what I want to do:

  • Find text starting after “Current Week”
  • Copy everything until it hits “ARCHIVE”
  • Paste this section into a different doc

I’ve tried tweaking my existing code, but I’m stuck. Anyone know how to pinpoint a specific part of a Google Doc with Apps Script? Here’s a simplified version of what I’ve got so far:

function copyDocSection() {
  const sourceDoc = DocumentApp.openById('source_id').getBody();
  const targetDoc = DocumentApp.openById('target_id').getBody();
  
  // Need help here to select and copy the right part
  
  // Then paste it into the target doc
}

Any ideas would be super helpful! Thanks in advance!

I’ve tackled this kind of task before, and here’s what worked for me:

Use findText() to locate ‘Current Week’ and ‘ARCHIVE’. Once you’ve got those positions, you can use getChildIndex() to figure out where they are in the document structure. Then, it’s a matter of looping through the elements between those indices and copying them over.

One thing to watch out for: make sure you handle cases where those marker texts might not exist. You don’t want your script crashing if someone’s changed the document structure.

Also, consider using a Blob to transfer the content. It’s more efficient for larger chunks of text. You might need to rebuild some of the formatting in the target doc, but it’s generally faster than element-by-element copying.

Hope this helps point you in the right direction!

I have encountered a similar task in one of my projects. One effective approach is to use the findText() method to locate the starting and ending markers, namely “Current Week” and “ARCHIVE”. Once these markers are found, you can determine their positions in the document using getChildIndex() and then iterate through the elements between them. Handling potential cases where the markers are missing is important to avoid errors. This method provides a controlled extraction of the desired content, ensuring only the specific section is transferred.

hey laura, i’ve done smth similar before. u can use findText() to locate ur start/end points. then getElement() and getNextSibling() to grab everything in between. might wanna add some error checking too incase the markers arent there. lemme know if u need more help!