My goal is to replace a piece of text in a Google Drive document with the contents of another document.
I have been able to insert the document at a certain position in the other document, but I'm having trouble determining the child index of the piece of text I want to replace. Here is what I have so far:
function replace(docId, requirementsId) {
var body = DocumentApp.openById(docId).getActiveSection();
var searchResult = body.findText("<<requirementsBody>>");
var pos = searchResult.?? // Here I would need to determine the position of the searchResult, to use it in the insertParagraph function below
var otherBody = DocumentApp.openById(requirementsId).getActiveSection();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = otherBody.getChild(j).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ) {
body.insertParagraph(pos,element);
} else if( type == DocumentApp.ElementType.TABLE ) {
body.insertTable(pos,element);
} else if( type == DocumentApp.ElementType.LIST_ITEM ) {
body.insertListItem(pos,element);
} else {
throw new Error("According to the doc this type couldn't appear in the body: "+type);
}
}
};
Any assistance would be greatly appreciated.
findText()
returns a RangeElement.
You can use
var r = rangeElement.getElement()
to get the element containing the found text.
To get its childIndex you can use
r.getParent().getChildIndex(r)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With