Google Docs - Format Matching Text Script
Revision as of 18:36, 14 November 2022 by NoskeWiki (talk | contribs) (Created page with "==About== {{DaughterPage|mother=Google Docs, and is related to: JavaScript}} This demos a <b>Google Docs Add On / App Script</b> to format text. :) image:Google_d...")
About
NOTE: This page is a daughter page of: Google Docs, and is related to: JavaScript
This demos a Google Docs Add On / App Script to format text. :)
File:Google docs addon format text.png
What the thing looks like after a run
Background and Instructions
The right API to help is the Google Docs API... but that's slow to process, so here's what you need to do to create a new menu item that does something:
- Create a brand new Google Doc ............... (tip: Try typing into Chrome: docs.new)
- Click menu bar: Extensions > App Scripts.
- Enter the javascript code below into the Script Editor and hit "Save" and "Deploy" (as "Editor Add-On")
..... (tip: You can hit the play button to test one of the functions before saving) - Reload your Google Doc and approve permissions.
- Run the Script by clicking the new menu item that appears: Special Formatting > Format Stat Numbers.
(see pictures of this process)
Google Docs Add On - Format Matching Text Script
Code.gs
/**
* @fileoverview This script uses Google Docs API to forat certain strings.
* Instrutions and documentation for the script lives at:
* http://andrewnoske.com/wiki/Google_Docs_-_Format_Matching_Text_Script
*/
/**
* Formats the matching strings with .
* param@ {string} findMe Regex string to look for.
* param@ {string} color Color string in the form "#ffffff".
* param@ {number} fontSize The font size to set.
*/
function formatMatchingStrings(findMe, color, fontSize) {
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
// Find and color each match:
var foundElement = body.findText(findMe);
while (foundElement != null) {
// Color the next match:
var foundText = foundElement.getElement().asText();
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Change the color and font size:
foundText.setForegroundColor(start, end, color);
foundText.setFontSize(start, end, fontSize);
// Find the next match:
foundElement = body.findText(findMe, foundElement);
}
}
/**
* Formats furball numbers.
*/
function formatFurballNumbers(findMe, color, fontSize) {
formatMatchingStrings('±.*', '#aaaaff', 8);
}
/**
* Called when doc opens. Creates menu iteam for "Special Formatting".
*/
function onOpen() {
// Add a menu item:
DocumentApp.getUi().createMenu('Special Formatting')
.addItem('Format Furball Numbers', 'formatFurballNumbers')
.addToUi();
}