Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing words in Google Docs with Google AppScript

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.

like image 858
Yellvis Avatar asked Oct 28 '25 11:10

Yellvis


1 Answers

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.

like image 126
Charlie Patton Avatar answered Oct 31 '25 13:10

Charlie Patton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!