1

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]+');
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
JoshDG
  • 3,871
  • 10
  • 51
  • 85

1 Answers1

0

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.

Vyacheslav Pukhanov
  • 1,788
  • 1
  • 18
  • 29
  • Hey thanks for your response! I edited my original post to comply with what you said but it still isn't progressing. Any ideas? – JoshDG Sep 12 '15 at 16:44
  • @JoshDG sorry it took longer than expected, was testing things out. Have an update on the topic (updated answer), so you can't achieve this as for now. – Vyacheslav Pukhanov Sep 12 '15 at 17:09
  • OK Thanks for your help! I'll have to edit as I go I guess rather than editing at the end – JoshDG Sep 12 '15 at 17:14