Home > Software design >  Google apps script for docs: Log text selection as string
Google apps script for docs: Log text selection as string

Time:12-23

I'm trying to return the words in a text selection as a string in google docs. I can't figure out how to return anything other than the entire body of text in an element, and it seems like the smallest element is a paragraph. I ned smaller.

Attempt 1:

function printSelection1 () {
var string = DocumentApp.getActiveDocument().getText();
Logger.log(string);
}

This returns the entire body of the document, rather than the selection, as a string.

Attempt 2:

function printSelection2 () {
var selection = DocumentApp.getActiveDocument().getSelection();
var string =selection.asString();
Logger.log(string);
}

Error message: "TypeError: selection.asString is not a function."

Attempt 3:

function printSelection4 () {
var selection = DocumentApp.getActiveDocument().getSelection();
var getelements =selection.getSelectedElements();
var string = getelements.toString();
Logger.log(string);
}

This returns the string "RangeElement," rather than the string of the selection itself.

I feel like I'm close. Or maybe I'm not?

CodePudding user response:

This should help.

function getSelectedText() {
  var text = DocumentApp.getActiveDocument()
    .getSelection() 
    .getRangeElements()
    .map((element) => element.getElement().asText().getText())
    .join(" ");

  Logger.log(text);
}

CodePudding user response:

Would something like this suffice:

function printSelection() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var range = selection.getRange();
    var string = range.getText();
    Logger.log(string);
  } else {
    Logger.log("No text is selected.");
  }
}

EDIT: Judging by the error, it seems that getRange() is not available for the seleciton object...

You can try to use the getStartOffset() and getEndOffset():

function printSelection() {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var startIndex = selection.getStartOffset();
    var endIndex = selection.getEndOffset();
    var document = DocumentApp.getActiveDocument();
    var string = document.getText().substring(startIndex, endIndex);
    Logger.log(string);
  } else {
    Logger.log("No text is selected.");
  }
}
  • Related