Hey, friends today I will teach you How to find and replace text in the Word document’s header and footer section using the Google Document API. Document Studio’s upcoming release will include support for inserting markers in the header, footer, and footnotes sections of your Microsoft Word template. This placeholder text will be automatically replaced with actual values from Google Sheets or Google Forms by the add-on.
so let get started with today Code snippets. Getting different problems is altogether gives a very different experience. today the Code snippets I am going to share with you is How to find and replace text in the Word document’s header and footer section using the Google Document API.
You might also like our trending code snippets
- How to Delete Blank Rows from Tables in your Google Documents
- How to Change the Font in your Google Documents with Apps Script
- How to Convert Column Number (e.g. 28) to Column Letter (e.g. AB) in Google Sheets
- Create a Telegram Bot for Sending Notifications using Google Apps Script
Replace Header and Footer with Document API
This Apps Script snippet searches for and replaces multiple blocks of text in the header and footer sections of your Google Document using the Google Docs API. The DOCUMENT section is the parent of the header and footer sections.
const replaceHeaderFooter = () => {
// Returns the document with the specified ID
const doc = DocumentApp.openById("DOCUMENT ID");
// Retrieves the headers's container element which is DOCUMENT
const parent = doc.getHeader().getParent();
for (let i = 0; i < parent.getNumChildren(); i += 1) {
// Retrieves the child element at the specified child index
const child = parent.getChild(i);
// Determine the exact type of a given child element
const childType = child.getType();
if (childType === DocumentApp.ElementType.HEADER_SECTION) {
// Replaces all occurrences of a given text in regex pattern
child.asHeaderSection().replaceText("{{Company}}", "Digital Inspiration");
} else if (childType === DocumentApp.ElementType.FOOTER_SECTION) {
// Replaces all occurrences of a given text in regex pattern
child.asFooterSection().replaceText("{{Copyright}}", "© Amit Agarwal");
}
}
// Saves the current Document.
// Causes pending updates to be flushed and applied.
doc.saveAndClose();
};
If the current document lacks a header section, the getHeader() function will return null; therefore, you may want to include additional checks to determine whether a document has a header or footer.