简体   繁体   English

Google Apps Script 在 Google Docs 的特定部分下提取文本

[英]Google Apps Script extract text under particular section in Google Docs

I have a Google Doc with 3 sections and there is text under each section header text.我有一个包含 3 个部分的 Google 文档,每个部分标题文本下都有文本。

在此处输入图片说明

2 sections with the same header text but different text and I would like to extract text under the last section.具有相同标题文本但文本不同的 2 个部分,我想提取最后一部分下的文本。 Is it possible that I can write script to read the "header" under the "Document Outline" that I need and extract the section only?我是否可以编写脚本来读取我需要的“文档大纲”下的“标题”并仅提取该部分?

I tried script below and use .search() method to find "SECTION 01" however it return the position of 1st header in the document.我尝试了下面的脚本并使用.search()方法来查找“SECTION 01”,但是它返回文档中第一个标题的位置。

function extract_text() {
  const content = DocumentApp.openById("1MaWDAW2OrhNKNDesNIphb0hXQ1jWAbLrprpTRe4bCRw")
  .getBody()
  .getText()

  const position = content.search('Section 01')

  // result = 0
  console.log(position)
}

Solution解决方案

The method indexOf() has a second parameter called fromIndex that you can use to skip the first occurrence.方法indexOf()有一个名为fromIndex的第二个参数,您可以使用它来跳过第一次出现。

Code代码

const searchTerm = "Section 01"
const position = content.indexOf(searchTerm, content.indexOf(searchTerm) + 1);

Reference参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM