I'm trying to make a Google Apps Script that will highlight multiple choice answers in a Google Doc. Here's an example question:
Question....blah blah blah.
a. Answer 1
b. Answer 2
c. Answer 3
d. Answer 4
e. Answer 5
And here's what I've got so far for a script:
function highlight() {
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1nP6ra0zIMI3OB-zsTMbFybO2e7ajoYgQi8doDcurGew/edit?usp=sharing');
var style = {};
style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#E3E65B';
var text = doc.editAsText();
var result = text.findText(/^(a|b|c|d|e)\..*/gm).getElement();
for (var i = 0; i < result.length; i++){
result[i].setAttributes(style);
}
}
But it just gives me "Cannot call method "getElement" of null".
You are not expecting a no matched result. Try this instead.
function highlight() {
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1nP6ra0zIMI3OB-zsTMbFybO2e7ajoYgQi8doDcurGew/edit?usp=sharing');
var style = {};
style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#E3E65B';
var text = doc.editAsText();
if(text.findText(/^(a|b|c|d|e)\. Answer [0-9]+$/gm) !== "undefined")
{
var result = text.findText(/^(a|b|c|d|e)\. Answer [0-9]+$/gm)).getElement();
for (var i = 0; i < result.length; i++)
{
result[i].setAttributes(style);
}
}
else
{
//Do whatever. There is no element matched
}
}
On the other hand, the regex /^(a|b|c|d|e)\..*/gm
means:
Begins with a OR b OR c OR d OR e
, .
, any character 0 or more times (.*
). g
flag means that will continue searching after the first match. The m
flag means that $
and ^
can match the beginning of a line and the end of a line respectively.
So it will match something like this: a.anything
, b.66/qQ-.r...
, etc.
If you want to match something like a. Answer 1
, you should use:
/^(a|b|c|d|e)\.\s.+\s[0-9]+$/gm
If it is going to be always Answer
you could use:
/^(a|b|c|d|e)\.\sAnswer\s[0-9]+$/gm