I'm trying to build a named range from selected text in Google App Script for a Google Docs text. However, it is always taking the entire line as the element and building range for it. For example, if my text is Some sample text is added here in the doc
and if I have selected the first word i.e. Some
then I want the named range created for the text Some
only.
Following is the code I have written
const selection = DocumentApp.getActiveDocument().getSelection();
const selectedTextElements = [];
if (selection) {
const elements = selection.getSelectedElements();
for (let i = 0; i < elements.length; ++i) {
if (elements[i].isPartial()) {
const element = elements[i].getElement().asText();
const startIndex = elements[i].getStartOffset();
const endIndex = elements[i].getEndOffsetInclusive();
const rangeBuilder = DocumentApp.getActiveDocument().newRange();
rangeBuilder.addElement(element,startIndex,endIndex);
rangeBuilder.build();
DocumentApp.getActiveDocument().addNamedRange(rangeName,rangeBuilder);
}
}
}
Thank you!