I need the full text of a user-made selection in Google Docs which may stretch over multiple lines.
This is different from this question: Get user-selected text because in that question the request was to get the text of individual words or lines that are selected. I need to be able to handle multiple lines with the correct whitespace.
I wrote the code below, and it almost works, but it smashes the text from two lines together without a newline character (or anything) separating them. It also doesn't include tabs from the original text. I'm guessing there are other limitations I haven't come across!
function getSelectedText()
{
var selection = DocumentApp.getActiveDocument().getSelection();
if( !selection )
return "";
var selectedElements = selection.getRangeElements();
var theText = "";
for( var i=0; i < selectedElements.length; i++ )
{
var thisText = selectedElements[i].getElement().asText().getText();
if( selectedElements[i].isPartial() )
{
var thisText = thisText.substring( selectedElements[i].getStartOffset(), selectedElements[i].getEndOffsetInclusive() + 1)
}
theText += thisText;
}
return theText;
}
So let's say I have a document that looks like this with all the text selected by the user (with a tab in the second line):
Line 1
Line 2
My script will construct the string, "Line 1Line 2". The string I would like is, "Line 1\nLine 2" or "Line 1\rLine 2".