How do you change formatting within a google doc for multiple occurrences using findText()?

元气小坏坏 提交于 2021-02-10 22:23:21

问题


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).

I wrote the following:

  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
}

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!


回答1:


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
}

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




回答2:


You can replace everything in the entire body with this:

function testReplace() {
  var docBody = DocumentApp.getActiveDocument().getBody();
  docBody.replaceText(searchPattern, replacement);
};

Google Documentation - Replace Text



来源:https://stackoverflow.com/questions/32674241/how-do-you-change-formatting-within-a-google-doc-for-multiple-occurrences-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!