Skip to content

Instantly share code, notes, and snippets.

@synergychen
Created March 27, 2023 23:40
Show Gist options
  • Select an option

  • Save synergychen/b29956c17f6dc5f36c29229d994803c6 to your computer and use it in GitHub Desktop.

Select an option

Save synergychen/b29956c17f6dc5f36c29229d994803c6 to your computer and use it in GitHub Desktop.
function findAndHighlightText() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.getText();
const matchedTexts = text.match(/(-+)?\d+\.\d{2}% \[(-+)?\d+\.\d{2}, (-+)?\d+\.\d{2}\] %/g)
var positiveBgColor = "#ddffbb";
var positiveFontColor = "#008800";
var negativeBgColor = "#ffdbdb";
var negativeFontColor = "#ff0000";
var neutralBgColor = "#ffffff";
var neutralFontColor = "#777777";
for (let i = 0; i < matchedTexts.length; i++) {
var target = matchedTexts[i].replace(/\[/g, '\\[').replace(/\]/g, '\\]');
var foundText = body.findText(target);
var negativeSignCount = (target.match(/-/g) || []).length
var isNegative = negativeSignCount === 3
var isPositive = negativeSignCount === 0
var bgColor, fontColor
if (isNegative) {
bgColor = negativeBgColor
fontColor = negativeFontColor
} else if (isPositive) {
bgColor = positiveBgColor
fontColor = positiveFontColor
} else {
bgColor = neutralBgColor
fontColor = neutralFontColor
}
while (foundText != null) {
var startOffset = foundText.getStartOffset();
var endOffset = foundText.getEndOffsetInclusive();
var textRange = foundText.getElement().asText();
textRange.setBackgroundColor(startOffset, endOffset, bgColor);
textRange.setForegroundColor(startOffset, endOffset, fontColor);
foundText = body.findText(target, foundText);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment