如何使用findText()更改Google文档中多次出现的格式? [英] How do you change formatting within a google doc for multiple occurrences using findText()?

查看:68
本文介绍了如何使用findText()更改Google文档中多次出现的格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Google文档中查找文本,并用下标符号替换-将"a3"替换为a3,但现在设置为下标格式的3.

I am trying to find text within a google doc and replace with a subscript notation - replace "a3" with a3 but with the 3 now formatted as a subscript.

根据答案此处我编写了一些有效的代码,但仅替换了所有实例的第一个实例(有些重复).

based on the answer here I wrote some code that is working but only replaces the 1st instance of any occurrence (some are repeated).

我写了以下内容:

  for (var k=0; k<subscriptsReplace.length; k++) {
      subscript = ' a'+subscriptsReplace[k];
      find = ' a'+subscriptsReplace[k]+' ';
             Logger.log(find)
  var element = body.findText(find);
  if(element){ // if found a match
    var start = element.getStartOffset();
    var text = element.getElement().asText();
    text.replaceText(find, subscript);
    text.setTextAlignment(start+2, start+2, DocumentApp.TextAlignment.SUBSCRIPT);
    Logger.log("found one");
} // else do nothing
}

请注意, subscriptsReplace 是一个数组,其中包含整个文档中所有下标的编号.

note that subscriptsReplace is an array that contains all the numbers of the subscripts throughout the document.

通过查看日志,我无法弄清为什么它没有得到重复,我知道它没有对重复执行条件操作-因此它不会重新替换已经替换的下标.

I cannot figure out why it's not getting the repeats, by looking at the logs, I know that it's not running the conditional on the repeats - so it's not re-replacing the same subscript it already replaced.

有人可以看到发生了什么吗?谢谢你!

can someone see what's going on? THank you!

推荐答案

最终,问题是使用replaceText()替换了整个文档中所有出现的文本,因此无法找到和替换该文本.第一次迭代后进行格式化.

Ultimately the issue was that using replaceText() was replacing all the occurences of the text throughout the document and therefor, it wasn't available to find and replace the formatting after the 1st iteration.

这是替换所有情况的代码:

Here's the code that replaced all occurences:

  for (var k=0; k<subscriptsReplace.length; k++) {
       find = 'a'+subscriptsReplace[k]+'_';
       var element = body.findText(find);
  if(element){ // if found a match
       var start = element.getStartOffset();
       var text = element.getElement().asText();
       text.setTextAlignment(start+1, start+1, DocumentApp.TextAlignment.SUBSCRIPT);
       text.deleteText(start+2, start+2);
  } // else do nothing
}

您将看到,而不是替换,我添加了一个特殊字符"_"作为查找的标记,然后在我重新格式化为下标时一次使用deleteText()来摆脱它们

you'll see that rather than replacing, I added a special character "_" as a marker to find and then used deleteText() to get rid of them 1 at a time as I reformatted into subscripts

这篇关于如何使用findText()更改Google文档中多次出现的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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