Apps Script Lesson Select Emails using Regex on Doc Body text apply style for highlighting selection

Highlight emails in a Doc using Regex on Doc Body Contents

Select all matching results from a Regex for email patterns.  Creates an array of the emails contained in the doc, then applies styling to the email.  Highlight the matching results with a yellow background and black text.

function onOpen(){






function highlighter(){

 const doc = DocumentApp.getActiveDocument();

 const body = doc.getBody();

 const bodyText = body.getText();

 const exp = /([A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+)/gi;

 const results = bodyText.match(exp);

 const style = {};

 style[DocumentApp.Attribute.FOREGROUND_COLOR] = ‘#000000’;

 style[DocumentApp.Attribute.BACKGROUND_COLOR] = ‘#FFFF00’;

 const paras = body.getParagraphs();

 paras.forEach(p =>{

   results.forEach(email =>{

     const textLoc = p.findText(email);

     if(textLoc != null && textLoc.getStartOffset() != -1){







Leave a Comment