Home > database >  How to find and replace special characters in Google Doc using Apps Script?
How to find and replace special characters in Google Doc using Apps Script?

Time:07-15

I need to replace certain sets of characters in a Google Doc with others. I'm new to Javascript so I'm sure there's a better way of doing this, but here's the code I've been using: old_characters is what's in the Doc and new_characters is what I'm replacing them with, and I've capped the loop at 40 because that's the max number of times I need to do it in the doc.

const doc = DocumentApp.getActiveDocument()
const body = doc.getBody();

var z = 1

while (z < 41) {
    body.findText(old_characters)
      .getElement()
      .asText()
      .setText(new_characters)
  z  
}
  doc.saveAndClose

It works fine for some sets of characters, like changing " AM" (from 5 AM) to "am" (to 5am). But I run into issues when trying to change ".." into "." or ":00" into "" (to get rid of double periods, and change times from 5:00 AM to 5am). Nothing happens.

I've used ".." and regex /.{2}/ to identify the double period, for example, and try to replace with "." but they aren't replaced.

I'd also like to delete a bunch of empty space from the end of the document, without deleting the occasional empty line earlier in the doc, and not sure how.

CodePudding user response:

Probably you could make the changes with this code:

function main() {
  var doc = DocumentApp.getActiveDocument();

  var old_characters = 'AM';
  var new_characters = 'am';
  doc.replaceText(old_characters, new_characters);

  old_characters = '\\.\\.';
  new_characters = '.';
  doc.replaceText(old_characters, new_characters);

  old_characters = ':00';
  new_characters = '';
  doc.replaceText(old_characters, new_characters);
}

Or the same algorithm in more fancy style:

function main() {
  const doc = DocumentApp.getActiveDocument();

  const replaces = [
    {what: 'AM',     to: 'am'},
    {what: '\\.\\.', to: '.'},
    {what: ':00',    to: ''},
  ]

  replaces.forEach(replace => doc.replaceText(replace.what, replace.to));
}
  • Related