I have a Google Doc where I want to remove everything (including tables and horizontal lines) after a certain keyword, including the keyword itself. However, the script I have now isn't working correctly and I have no clue why. It's only removing a few paragraphs and not everything. Any insight?
function deleteContent() {
var keyword = "%delete%";
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var found = false;
for (var i = 0; i < body.getNumChildren(); i++) {
var element = body.getChild(i);
if (element.getType() == DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getText() == keyword) {
found = true;
for (var j = i+1; j < body.getNumChildren(); j++) {
body.getChild(j).removeFromParent();
}
break;
}
}
}
I believe your goal is as follows.
%delete%
in Google Documents.When this script is reflected in your script, how about the following modification?
function deleteContent() {
var keyword = "%delete%";
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var numChildren = body.getNumChildren();
for (var i = 0; i < numChildren; i++) {
var element = body.getChild(i);
if (element.getType() == DocumentApp.ElementType.PARAGRAPH && element.asParagraph().getText() == keyword) {
for (var j = numChildren - 2; j >= i; j--) { // Modified
body.getChild(j).removeFromParent();
}
break;
}
}
}
By the way, in the current stage, the last paragraph cannot be deleted using the Document service (DocumentApp). Ref Please be careful about this. By this, I used var j = body.getNumChildren() - 2
as the initial condition.
About How would you include also deleting the keyword?
, I modified the above script. j >= i + 1
was modified to j >= i
.