I'm having trouble figuring out how find/next works in Google Apps Script. In the example here I'm trying to superscript the numbers in a list of authors. But my loop doesn't exit, presumably because it just keeps selecting the first item over and over again.
EDIT: Updated with 'from' parameter: Loop still does not exit? I added some log comments and it is still getting stuck on the first item (start offset and end offset are both = 10)
var doc = DocumentApp.create('test1');
var authors = "Josh Smith1, Zach Johnson2";
var paragraph = doc.getBody().appendParagraph(authors);
var text = paragraph.editAsText();
var range = text.findText('[0-9]+');
while(range)
{
Logger.log("START OFFSET: " + range.getStartOffset());
Logger.log("END OFFSET: " + range.getEndOffsetInclusive());
Logger.log("PARAGRAPH ELEMENT: "+ paragraph.editAsText().getText());
text.setTextAlignment(range.getStartOffset(),range.getEndOffsetInclusive(),DocumentApp.TextAlignment.SUPERSCRIPT);
range = text.findText('[0-9]+', range);
}
ORIGINAL
var authors = "Josh Smith1, Zach Johnson2";
var paragraph = doc.getBody().appendParagraph(authors);
var text = paragraph.editAsText();
var range = text.findText('[0-9]+');
while(range)
{
text.setTextAlignment(range.getStartOffset(),range.getEndOffsetInclusive(),DocumentApp.TextAlignment.SUPERSCRIPT);
range = text.findText('[0-9]+');
}
INFO: The solution provided here is correct, but as for now there is a bug in Google Apps Script, which would make this code to loop. There is no fix to the date.
You are correct about that it's stuck on the first item. However, it's really easy to fix. findText()
function can take one or two parameters. The first parameter is always search pattern and the second optional parameter is a place from where it should start searching. So the fixed code is:
var authors = "Josh Smith1, Zach Johnson2";
var paragraph = doc.getBody().appendParagraph(authors);
var text = paragraph.editAsText();
var range = text.findText('[0-9]+');
while(range)
{
text.setTextAlignment(range.getStartOffset(),range.getEndOffsetInclusive(),DocumentApp.TextAlignment.SUPERSCRIPT);
range = text.findText('[0-9]+', range);
}
That should fix it for you.