Use replaceText() for selected text, not the entir

2019-07-03 15:48发布

How can I use replaceText() to replace a word in selected area of an element, the following code will replace matches in an entire element not the selected area. any ideas to fix this?

I know I can use isPartial() to separate partial selection but couldn't figure out how to replace the selected text.

function test() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (!selection) {
    DocumentApp.getUi().alert('Cannot find a selection in the document.');
    return;
  }

 var selectedElements = selection.getSelectedElements();
 for (var i = 0; i < selectedElements.length; ++i) {
  var selectedElement = selectedElements[i];
  //if (selectedElement.isPartial()) {
    selectedElement.getElement().asText().replaceText("alpha","beta");
    selectedElement.getElement().asText().replaceText("gamma","delta");
  //}
}
}

1条回答
可以哭但决不认输i
2楼-- · 2019-07-03 16:17

Use

selectedElement.getElement().replaceText("alpha","beta");
查看更多
登录 后发表回答