How to Find and Replace Text in Google Docs with RegEx Search Patterns
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();
};
Amit Agarwal
Google Developer Expert, Google Cloud Champion
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.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory