如何搜索和替换水平线和换行符

How to search and replace a horizontal rule and linebreaks

我需要自动删除 google 文档中被 6 个换行符(3 个换行符和 3 个换行符)包围的水平线。

这段代码似乎在日志中放入了我要删除的正确换行符(这是第一步):

function myFunction() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody().getText();
var pattern = /\s\s\s\s/g; 
  while (m=pattern.exec(body)) { Logger.log(m[0]); }
}

我有两个问题:

Horizontal rule 是段落中的一个元素(或者有时是列表项中的一个元素)。由于它不是文本,因此无法通过正则表达式找到或替换它。我们应该搜索文档主体中专门安排的对象,如果找到则将其删除。

考虑以下代码示例:

function deleteHR() {
  var body = DocumentApp.getActiveDocument().getBody();
  var hr = null, hrArray = [], countDeleted = 0;

  // Collect all horizontal rules in the Document
  while (true) {
    hr = body.findElement(DocumentApp.ElementType.HORIZONTAL_RULE, hr);
    if (hr == null) break;
    hrArray.push(hr);
  }

  hrArray.forEach(function(hr) {
    var p = hr.getElement().getParent();
    // Get empty paragraphs as siblings (if any)
    var prevSiblings = getSiblings(p, 3, true),
        nextSiblings = getSiblings(p, 3, false);
    // Define a short function for batch deleting items
    function remove(e) {
      e.removeFromParent();
    }
    // If empty paragraphs exist (3 before and 3 after)
    if (prevSiblings.length == 3 && nextSiblings.length == 3) {
      // then delete them as well as the rule itself
      hr.getElement().removeFromParent();
      prevSiblings.forEach(remove);
      nextSiblings.forEach(remove);
      countDeleted++;
    }
  });
  // Optional report
  Logger.log(countDeleted + ' rules deleted');
}


// Recursive search for empty paragraphs as siblings
function getSiblings(p, n, isPrevious) {
  if (n == 0) return [];
  if (isPrevious) {
    p = p.getPreviousSibling();
  } else {
    p = p.getNextSibling();
  }
  if (p == null) return [];
  if (p.getType() != DocumentApp.ElementType.PARAGRAPH) return [];
  if (p.asParagraph().getText().length > 0) return [];
  var siblings = getSiblings(p, n - 1, isPrevious);
  siblings.push(p);
  return siblings;
}

Main 函数 deleteHR() 完成所有工作。然而,使用另一个单独的函数 getSiblings() 来递归搜索空段落似乎很有帮助。也许,这种方式不是唯一的,但它确实有效。