Google Apps脚本用于删除2个关键字之间的文字/行

时间:2014-03-25 16:35:47

标签: google-apps-script google-docs

我想使用谷歌应用脚​​本将其他文档的完整内容复制到当前文档,然后执行一些清理。

我能想到的工作流程是:

1. clear current document

    DocumentApp.getActiveDocument().getBody().editAsText().setText('');

2. copy content from an other document (not sure what is the syntax)

3. find and delete <keyword> ..... </keyword>. It can be single line or
   pan across multiple lines and having table or diagram in between. eg.

Before
------
This is a <keyword>big black</keyword> cat.

<keyword>
Title
... table here
... diagram here
</keyword>

End of doc.


After
-----
This is a cat.


End of doc.

我需要帮助创建第2项&amp;项目的Google应用脚本上面的#3。

2 个答案:

答案 0 :(得分:0)

对于第3项,这是我的工作代码:

function deleteSection(keyword) {

  var start = ' *\<' + keyword + '\> *';
  var end   = ' *\<\/' + keyword + '\> *';

  var bodyElement = DocumentApp.getActiveDocument().getBody();
  var found = 0;

  // have to do reverse else the result is incorrect
  var totalchildren = bodyElement.getNumChildren();
  for (var i=totalchildren-1; i >= 0; i--) {
    if (found == 0) {
      if (bodyElement.getChild(i).asText().findText(end) !== null) {
        bodyElement.getChild(i).asText().replaceText(".*"+end,"");
        if (bodyElement.getChild(i).asText().findText("^ *$") !== null) {
          bodyElement.getChild(i).removeFromParent();
        }
        found = 1;
      }
    } else {
      if (bodyElement.getChild(i).asText().findText(start) !== null) {
        bodyElement.getChild(i).asText().replaceText(start+".*","");
        if (bodyElement.getChild(i).asText().findText("^ *$") !== null) {
          bodyElement.getChild(i).removeFromParent();
        }
        found = 0;
      } else {
        bodyElement.getChild(i).removeFromParent();
      }
    }  
  }
}

答案 1 :(得分:0)

对于#3,我有一个很好的解决方案。

在Google文档中,文字为:

Quero que todo o texto a seguir suma:

start
TEXTO QUE QUERO QUE SUMA
end

Será que deu certo??

在谷歌脚本中:

function BoldBetweenTags() {
var testeid = '1fltAxuhgfUOOdRvvIyXfLz13gxPDvtugUMyAGOK0jcE';
var body = DocumentApp.openById(testeid).getBody();
var text = body.editAsText();
var para = body.getParagraphs();

var startTag = 'start';
var endTag = 'end'

var del = "no";  

  for(var i in para){  
  Logger.log('Parágrafo: '+i)
    var from = para[i].findText(startTag);
    var to =  para[i].findText(endTag);
    if (from != null){var del = "yes";  para[i].editAsText().removeFromParent();}
    if (from == null && to == null && del == "yes"){para[i].editAsText().removeFromParent();}
    if (to != null){var del = "no";  para[i].editAsText().removeFromParent();}
}}

对于#2,你需要

var folder =  DriveApp.createFolder("name of the folder");
var rep = DriveApp.getFileById('your ID');
var repi = rep.makeCopy("name of your new document", folder);

这对我有用