2022-12-23

Google apps script for docs: Log text selection as string

I'm trying to return a specific 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 a document.

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?



No comments:

Post a Comment