2013-10-04 8 views
5

Moim celem jest zastąpienie fragmentu tekstu w dokumencie na Dysku Google treścią innego dokumentu.Uzyskaj indeks potomny wyszukiwanego tekstu w google API script

Byłem w stanie wstawić dokument w określonej pozycji w innym dokumencie, ale mam problem z określeniem indeksu podrzędnego fragmentu tekstu, który chcę zastąpić. Oto, co mam do tej pory:

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); 
    } 
} 


}; 

Każda pomoc będzie bardzo ceniona.

Odpowiedz

5

findText()

zwraca RangeElement.

Można użyć

var r = rangeElement.getElement()

dostać element zawierający znalezionego tekstu.

Aby uzyskać jego childIndex można użyć

r.getParent().getChildIndex(r) 
2

Dzięki odpowiedź Bruce'a udało mi się wymyślić rozwiązanie tego problemu, jednak gdybym wstawiania elementów z innego dokumentu, co potrzebne, aby rzeczywiście znaleźć indeks rodzica znalezionego tekstu, ponieważ znaleziony tekst był po prostu elementem Tekstu wewnątrz elementu akapitu. Musiałem więc znaleźć indeks elementu akapitowego, a następnie wstawić nowe elementy w odniesieniu do tego akapitu.

Kod wygląda następująco:

var foundTag = body.findText(searchPattern); 
    if (foundTag != null) { 
    var tagElement = foundTag.getElement(); 
    var parent = tagElement.getParent(); 
    var insertPoint = parent.getParent().getChildIndex(parent); 
    var otherBody = DocumentApp.openById(requirementsId).getActiveSection(); 
    var totalElements = otherBody.getNumChildren(); 

    for(var j = 0; j < totalElements; ++j) { 
    ... then same insertCode from the question above ... 
     insertPoint++; 
    } 
+0

Gdy jest to obraz inline przed umieszczeniem findText, daje indeks dziecko akapitu przed obrazem, a nie po obrazie jak potrzebne. Czy jest w pobliżu praca? –

Powiązane problemy