从文档的第二条水平线向下删除所有内容 [英] Deleting all content down from the second horizontal line in a document

查看:68
本文介绍了从文档的第二条水平线向下删除所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本,以从页面中向下删除所有文本/内容.您可以在下面看到当前文档.

I'm trying to create a script to delete all text/content downwards from a page. Below you can see the current document.

当前,我具有脚本设置,以便它可以删除所有内容,包括"STARTHERE"文本中的所有内容.但是,我希望它从图像中的第二条水平线中删除,但是不包括该线.

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.

  1. 关于如何从第二条水平线中删除的任何想法?
  2. deleteText startOffset和endOffsetInclusive到底是什么意思?是行号还是?

上一个脚本:

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

推荐答案

您将需要完全改变您的方法,因为findText仅找到文本,而水平线不是文本.这是一种特殊的文档元素, Horizo​​ntalRule .

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.

(由于您询问:startOffset和endOffsetInclusive是元素内的字符计数;例如,如果在包含大红狗"的段落中找到文本"red",则startOffset为6,endOffset为9.这些都没有帮助)

(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)

这是我的方法:遍历Paragraph元素,寻找包含Horizo​​ntalRule元素的元素(使用

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.

有一个问题是,Apps脚本无法删除文档的最后一段;因此,我会提前添加空的段落,并且不要删除它.

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

这篇关于从文档的第二条水平线向下删除所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆