Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active April 1, 2019 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/30e8c778eb1102f651550b2345b6f3c0 to your computer and use it in GitHub Desktop.
Save tanaikech/30e8c778eb1102f651550b2345b6f3c0 to your computer and use it in GitHub Desktop.
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];
      requests.push({
      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);
  }
}

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment