0
votes

Trying to write a function that pulls text between <> brackets in a document, writes to html and allows the user to replace the bracketed text with a user input field (via the find and replace function). Having trouble getting the actual bracketed text from the google doc. The closest I have gotten is returning the paragraph the bracketed text is in, but that does not work because then the entire paragraph gets replaced instead of only the bracketed text.

This is the most recent error:

TypeError: Cannot find function getStartOffset in object Text. (line 11, file "Code", project "Find and Replace Script")

function doGet() {

  var docURL = DocumentApp.openByUrl('XXXX')
  var body = docURL.getBody();

  var fel0 = body.findText('<*>')
  var el0 = fel0.getElement(); 
  var startOffset = el0.getStartOffset();
  var endOffset = el0.getEndOffsetInclusive();
  var text = el0.asText().getText()
    if (elements[0].isPartial())
      text = el0.substring(startOffset,endOffset+1);

  var template = HtmlService.createTemplateFromFile('urlinput.html');
  template.el0 = el0;
  return template.evaluate();
}

function findreplace(form){
  var docURL = DocumentApp.openByUrl('XXXX')
  var body = docURL.getBody();
  body.replaceText(body.findText('<*>',fel0).getElement().asText().getText())

}

How do I get the actual found text from that body.findText('<*>') object? A big part that makes this difficult is the * wildcard between the <> brackets.

1

1 Answers

1
votes

Try this:

This is just a quick little example to help you to get past your current problem.

function findAndReplace(){
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var rel1=body.findText('<.*>');
  var el1=rel1.getElement();
  var t=el1.asText().getText();
  var x=rel1.getStartOffset();
  var y=rel1.getEndOffsetInclusive();
  var p=rel1.isPartial();
  el1.asText().replaceText('<.*>', 'You\'ve been replaced.');
  //Logger.log('\nt:%s\nx:%s\ny:%s\np:%s',t,x,y,p?'true':'false');
  //var end="is near";
}

This also works:

function findAndReplace(){
  DocumentApp.getActiveDocument().getBody().replaceText('<.*>', 'You\'ve been replaced.');
}

This is what you actually asked for:

As usual, I read some of the problem and then went off an did what I wanted to do. I guess you wanted to get the text. So here's another short example.

function findMyText(){
  var body=DocumentApp.getActiveDocument().getBody();
  var rel=body.findText('<.*>');
  var el=rel.getElement();
  var eltxt=el.asText().getText();
  var txt=eltxt.slice(rel.getStartOffset()+1,rel.getEndOffsetInclusive())
  DocumentApp.getUi().alert(txt);
}

I think your only problem was that you needed the .* which means zero or more of any character. The search pattern is a regular expression enclosed in quotes. I hope this helps.