Search code examples
google-apps-scriptgoogle-docs

How to delete selected text in a Google doc using Google Apps Script


In a Google document is there a way to delete selected text with Google Apps Script? The find criterion for the text to delete is not a string, but instead is relative to a bookmark. This question is related to a workaround for my open question at https://webapps.stackexchange.com/questions/166391/how-to-move-cursor-to-a-named-bookmark-using-google-apps-script).

Here is code I wish worked.

function UpdateBookmarkedText() {
  var doc = DocumentApp.getActiveDocument();
  var bookmarks = doc.getBookmarks();   
  for (var i = 0; i < bookmarks.length; i++){
    // Delete the old text, one step in a longer process.
    var text = bookmarks[i].getPosition().getElement().asText().editAsText();
    var range = doc.newRange().addElementsBetween(text, 5, text, 7).build(); // arbitrary offsets for testing
    doc.setSelection(range);  // The selected range is successfully highlighted in the document.
    doc.deleteSelection();  // This command does not exist.
} }

This documentation seems relevant but is over my head: https://developers.google.com/docs/api/how-tos/move-text


Solution

  • Use deleteText()

    You may use the following script as the basis for your script:

    function deleteSelectedText() {
      var selection = DocumentApp.getActiveDocument().getSelection();
      if (selection) {
        var elements = selection.getRangeElements();
        if (elements[0].getElement().editAsText) {
          var text = elements[0].getElement().editAsText();
          if (elements[0].isPartial()) {
            text.deleteText(elements[0].getStartOffset(), elements[0].getEndOffsetInclusive());
          }
        }
      }
    }
    

    This is a modified version of the script featured in the Class Range guide. This modification works for selected sentences within a paragraph. Thus, the use of the for loop (in the sample script) is not anymore necessary since the script operates within a single element/paragraph.

    Optimized Script:

    function test() {
      var selection = DocumentApp.getActiveDocument().getSelection();
      var elements = selection.getRangeElements();
      var text = elements[0].getElement().editAsText();
      (selection && elements[0].getElement().editAsText && elements[0].isPartial()) ? text.deleteText(elements[0].getStartOffset(), elements[0].getEndOffsetInclusive()):null;
    }
    

    References: