Replace bold to italic in google docs using apps script

ぐ巨炮叔叔 提交于 2019-12-24 13:43:19

问题


How to achieve a find and replace a bold font to italic using app script for Google docs. Note that it has to replace only the bold ones to italic and not all the text.

Say. A sample text

A quick brown fox jumps over a lazy dog a quick brown fox jumps over a lazy dog a quick brown fox jumps over a lazy dog.


回答1:


This is slightly awkward because there is nothing like "text node in bold" in Google Documents; the Text element does not have much internal structure. The solution seems to be to loop over its characters and test each on being bold. When the ranges of bold text are identified in the loop, they are set to italic with setItalic method. At the end, bold is removed from all text.

function bold2italic() {  
  var doc = DocumentApp.getActiveDocument();
  var text = doc.getBody().editAsText();
  var startBold = 0;
  var bold = false; 
  for (var i = 0; i < text.getText().length; i++) {
    if (text.isBold(i) && !bold) {
      startBold = i;
      bold = true;
    }
    else if (!text.isBold(i) && bold) {
      bold = false;
      text.setItalic(startBold, i-1, true);
    }
  }
  if (bold) {
    text.setItalic(startBold, i-1, true);
  }  
  text.setBold(false);
}


来源:https://stackoverflow.com/questions/36346494/replace-bold-to-italic-in-google-docs-using-apps-script

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