GAS can be replaced with getActiveDocument (). GetSelection () right away?

My user has the following choices in his Gdoc.

enter image description here

Now, from the sidebar, he wants to replace the selection that he made in the document.
GAS question: if this can be done right away, something like:
   var selection = DocumentApp.getActiveDocument().getSelection()    selection.replace("newtext")
Or do I need to go through selection.getRangeElements()to remove them (or replace them) and then place the new text in this position?

+3
source share
1 answer

No, this is not possible (well, if so, it is not documented).

, , , . .. . (, ).

, ( Kaylan Translate script, .

function replaceSelection(newText) {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var elements = selection.getRangeElements();
    var replace = true;
    for (var i = 0; i < elements.length; i++) {
      if (elements[i].isPartial()) {
        var element = elements[i].getElement().asText();
        var startIndex = elements[i].getStartOffset();
        var endIndex = elements[i].getEndOffsetInclusive();
        var text = element.getText().substring(startIndex, endIndex + 1);
        element.deleteText(startIndex, endIndex);
        if( replace ) {
          element.insertText(startIndex, newText);
          replace = false;
        }
      } else {
        var element = elements[i].getElement();
        if( replace && element.editAsText ) {
          element.clear().asText().setText(newText);
          replace = false;
        } else {
          if( replace && i === elements.length -1 ) {
            var parent = element.getParent();
            parent[parent.insertText ? 'insertText' : 'insertParagraph'](parent.getChildIndex(element), newText);
            replace = false; //not really necessary since it the last one
          }
          element.removeFromParent();
        }
      }
    }
  } else
    throw "Hey, select something so I can replace!";
}
+2

All Articles