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(){
DocumentApp.getUi()
.createMenu(’emails’)
.addItem(‘Highlight’,’highlighter’)
.addToUi()
}
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){
textLoc.getElement().setAttributes(textLoc.getStartOffset(),textLoc.getEndOffsetInclusive(),style);
}
})
})
//Logger.log(paras);
}