Skip to content

Instantly share code, notes, and snippets.

@tanaikech tanaikech/
Last active Apr 1, 2019

What would you like to do?
Modify Searched Text to Small Capital Letters using Google Apps Script

Modify Searched Text to Small Capital Letters using Google Apps Script

This is a sample script for modifying the searched text to the small capital letters using Google Apps Script. Unfortunately, in the current stage, there are no methods for modifying the part of texts to the small capital letters in Document Service, yet. But when Google Docs API is used, this can be achieved.

When you use this script, please enable Google Docs API at Advanced Google Services and API console. You can see how to enable them at here

Sample script

function myFunction() {
  var searchText = "sample";

  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var id = doc.getId();

  // Retrieve all contents from Google Document.
  var obj = Docs.Documents.get(id, {fields: "*"});

  // In order to use at Google Docs API, create ranges of found texts.
  var foundElement = body.findText(searchText);
  var requests = [];
  while (foundElement != null) {
    var p = foundElement.getElement();
    if (p.getType() == DocumentApp.ElementType.TEXT) p = p.getParent();
    if (p.getType() == DocumentApp.ElementType.PARAGRAPH || p.getType() == DocumentApp.ElementType.LIST_ITEM) {
      var content = obj.body.content[body.getChildIndex(p) + 1];
      updateTextStyle: {
        textStyle: {smallCaps: true},
        range: {
          startIndex: content.startIndex + foundElement.getStartOffset(),
          endIndex: content.startIndex + foundElement.getEndOffsetInclusive(),
        fields: "smallCaps"},
    foundElement = body.findText(textToFind, foundElement);

  // Modify textStyle of found texts.
  if (requests.length > 0) {
    var resource = {requests: requests};
    Docs.Documents.batchUpdate(resource, id);


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.