Javascript 在Google文档中添加文本和删除文本(附加组件)

Javascript 在Google文档中添加文本和删除文本(附加组件),javascript,html,google-apps-script,google-api,Javascript,Html,Google Apps Script,Google Api,我们有一个Doc的附加组件,它将数据插入到文档中,我们还希望它在您再次单击按钮时删除文本,就像开关一样。正如现在一样,第二次、第三次按下按钮,以此类推。。它在已存在的文本上填充新文本 客户端: <div class="block" id="button-bar"> <button onclick="google.script.run.insertTextA();" id="TextA">Text A</button>

我们有一个Doc的附加组件,它将数据插入到文档中,我们还希望它在您再次单击按钮时删除文本,就像开关一样。正如现在一样,第二次、第三次按下按钮,以此类推。。它在已存在的文本上填充新文本

客户端:

<div class="block" id="button-bar">
          <button onclick="google.script.run.insertTextA();" id="TextA">Text A</button>
          <button onclick="google.script.run.insertTextB();" id="TextB">Text B</button>   
          </div>
function insertTextA() {
 var body = DocumentApp.getActiveDocument().getBody();
 var text = body.editAsText();
 text.insertText(11, 'There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..');                         
}

function insertTextB() {
 var body = DocumentApp.getActiveDocument().getBody();
 var text = body.editAsText();
 text.insertText(12, 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..');
}
试试这个:

function insertTextA() {
 var body = DocumentApp.getActiveDocument().getBody();
 var val = body.findText('There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..');
  if(val == null)
  {
   var text = body.editAsText();
   text.insertText(11, 'There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..');         
  }
  else
  {
    body.replaceText('There is no one who loves pain itself, who seeks after it and wants to have it, simply because it is pain..','');
  }
}

您试图删除它的目的是什么?非常有效,谢谢iJay为我指明了正确的方向,如果使用replaceText的if语句也可以,为什么我自己没有想到它:]