How to Find and Replace Text in Google Docs with RegEx Search Patterns

H
Published in: Google Docs - Regular Expressions - Google Apps Script

It is easy to search and replace text in Google Documents with the DocumentApp service of Google Apps Script. You can use use findText method with simple regular expressions to find text elements in the document that match a pattern and replace them with the specified text.

Here’s a simple code sample that replaces the first occurrence of the “GSuite” with “Google Workspace” in the active Google Document.

const searchAndReplaceInGoogleDocs = () => {
  const searchText = "GSuite";
  const replaceText = "Google Workspace";

  const document = DocumentApp.getActiveDocument();
  const documentBody = document.getBody();

  const searchResult = documentBody.findText(searchText);

  if (searchResult !== null) {
    const startIndex = searchResult.getStartOffset();
    const endIndex = searchResult.getEndOffsetInclusive();
    const textElement = searchResult.getElement().asText();
    textElement.deleteText(startIndex, endIndex);
    textElement.insertText(startIndex, replaceText);
  }

  document.saveAndClose();
};

All well and good but in some cases, this simple search and replace function may fail if the search text does not transform into a valid regular expression.

For instance, if you have a text block like Hello (World in the document (notice the extra open bracket) that you would like to replace with Hello World, the above snippet will fail with an error message that says Exception: Invalid regular expression pattern.

To get around the problem, it is a good idea to replace all the special characters in the search pattern that have a special meaning in the RegEx world. These include characters like hyphen, brackets, question marks or the plus symbol.

Our modified search and replace function would then become:

const escapeRegex = (str) => str.replace(/[-[\]/{}()*+?.\\^$|#]/g, "\\$&");

const searchAndReplaceInGoogleDocs = () => {
  const searchText = "Hello (World";
  const replaceText = "Hello World";

  const document = DocumentApp.getActiveDocument();
  const documentBody = document.getBody();

  const searchResult = documentBody.findText(escapeRegex(searchText));

  if (searchResult !== null) {
    const startIndex = searchResult.getStartOffset();
    const endIndex = searchResult.getEndOffsetInclusive();
    const textElement = searchResult.getElement().asText();
    textElement.deleteText(startIndex, endIndex);
    textElement.insertText(startIndex, replaceText);
  }

  document.saveAndClose();
};
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Google Docs - Regular Expressions - Google Apps Script

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube