问题
I'm trying to create a script to delete all text/content downwards from a page. Below you can see the current document.
Currently, I have the script set-up so that it deletes everything down and including from a text of, "STARTHERE". However, I want it to delete down from the second horizontal line in the image, however, not including the line.
- Any ideas on how to delete down from the second horizontal line?
- What does deleteText startOffset and endOffsetInclusive actually mean? Is it like a line number or?
Previous Script:
function removeText() {
var body = DocumentApp.getActiveDocument().getBody();
var rangeElement = body.editAsText();
var start = "STARTHERE";
var end = "ENDHERE";
var rangeElement1 = DocumentApp.getActiveDocument().getBody().findText(start);
var rangeElement2 = DocumentApp.getActiveDocument().getBody().findText(end);
if (rangeElement1.isPartial()) {
var startOffset = rangeElement1.getStartOffset();
var endOffset = rangeElement2.getEndOffsetInclusive();
rangeElement1.getElement().asText().deleteText(startOffset,endOffset);
}
}
回答1:
You'll need to change your approach completely, because findText
only finds text, and a horizontal line is not text; it is a special type of document element, HorizontalRule.
(Since you asked: startOffset and endOffsetInclusive are character counts within an element; e.g., if the text "red" is found in a paragraph that consists of "A big red dog", then startOffset is 6 and endOffset is 9. None of this helps here)
Here is my approach: loop over the Paragraph elements, looking for those that contain a HorizontalRule element (with findElement method). Once we found two such paragraphs, delete all subsequent ones.
There is a catch in that Apps Script can't delete the last paragraph of a document; for this reason I append empty paragraph ahead of time, and do not delete it.
function removeAfterSecondLine() {
var body = DocumentApp.getActiveDocument().getBody();
body.appendParagraph('');
var para = body.getParagraphs();
var ruleCount = 0;
for (var i = 0; i < para.length - 1; i++) {
if (ruleCount >= 2) {
body.removeChild(para[i]);
}
else if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
ruleCount++;
}
}
}
来源:https://stackoverflow.com/questions/47291817/deleting-all-content-down-from-the-second-horizontal-line-in-a-document