Ellen Siem
Ellen Siem

Reputation: 15

How to replace all elements of alphabetical list in google script for google doc

I want to automate some doc editing. Right now, I'm trying to replace elements of a list for a quiz that are incorrect with a ~

For example, let's say that in a document I have the following, and I've already marked the correct choice using an =.

The capital of Norway is:
a. Haifa
=Oslo
c. Lund
d. the Hague
e. Manitoba

I want to create a script that will replace a., c., d., and e. each with ~

I've tried creating a function that looks like this:

function incorrectAnswera(){
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText("a.", "~");
}

But it replaces every instance of "a" and the character that follows with ~. For example, Earth becomes E~th.

Upvotes: 0

Views: 146

Answers (1)

dwmorrin
dwmorrin

Reputation: 2744

Text.replaceText(searchPattern, replacement) uses regular expressions for the searchPattern, specifically Google's RE2 library.

As a regular expression, a. will match the letter "a" plus any character following it, because . is a special "wildcard" character in regular expressions that matches any character.

As a regular expression convention, you can remove the special meaning from the . character with a backslash: \.. However, because the Apps Script implementation takes a JavaScript string as input, you have to (annoyingly) add an extra backslash to get the desired effect.

a\\. matches the character sequence "a" followed by a period.

This will still cause havoc because if you have the sentence

In the rain, I use an umbrella.

it will be replaced with

In the rain, I use an umbrell~

To fix that, we need to specify that the line starts with our expression, and the ^ character is reserved for that.

^a\\. will only substitute when the line begins with "a" followed by a period.

To achieve your stated goal:

I want to create a script that will replace a., c., d., and e. each with ~

you'll also need to use a set of characters to match which you can define with [ and ].

To take your request at face value, the set would be [acde], however since you are already marking the correct answer with a =, perhaps just using the range "a" to "e" would be better: [a-e] (that includes all 5 letters from a to e).

As a final detail, if you want the option of having white space in front of your a. sequence, you can use \\s* to indicate "zero or more white space characters", however the replacement may remove the white space.

// mark the start of the correct answer with a "=" before running this function
function markIncorrectAnswers() {
  DocumentApp.getActiveDocument().getBody()
    .replaceText("^\\s*[a-e]\\.", "~");
}

Upvotes: 1

Related Questions