2

I am looking to create a macro that takes a certain set of characters, and replaces it with another set of characters. This would preferably occur while I'm typing. How would one go about writing this in Google AppScript?

Also, I do realize that this question is very similar to this one: auto find and replace in Google Docs App Script, but I would like it to be able to replace the set when it's within another word.

  • Related: [How to find and remove blank paragraphs in a Google Document with Google Apps Script?](https://stackoverflow.com/q/39962369/1595451) – Rubén Feb 05 '18 at 17:18
  • Thank you for the link @Rubén, but that is concerned with removing blank paragraphs rather than swapping out characters. – Peregrine Lennert Feb 05 '18 at 17:22
  • That Q&A could serve you to start writing a script to do what you are looking for. Currently this question is too broad. While a link to a similar question is included, questions should be self-contained, meaning the question should not force readers to look into another question to understand what is being asked. By the other hand the referred question hasn't a good answer and it isn't a good question (no upvotes). – Rubén Feb 05 '18 at 17:26
  • @Rubén I added the link to the other question as to state how my question was different. – Peregrine Lennert Feb 05 '18 at 17:34

1 Answers1

4

Real-time text replacement is problematic because it requires a way to automatically detect changes to the document. While spreadsheets support the onEdit trigger, docs do not. You can simulate this behavior, as demonstrated in this answer.

If real-time replacement is not a requirement, you can simply write a function to do a regex replacement, and add the function to the menu:

function replaceText(){
  var docBody = DocumentApp.getActiveDocument().getBody();
  docBody.replaceText('[Aa]pple','pear'); 
  //Will replace "apple", "Apple," "applesauce", "pineapple"
}

function onOpen(e){
  DocumentApp.getUi()
  .createMenu("Text Replacer")
  .addItem("Replace all Text", 'replaceText')
  .addToUi();
}

For help writing your regex, see this document.

Charlie Patton
  • 435
  • 2
  • 12