Google Apps Script to highlight multiple choice

情到浓时终转凉″ 提交于 2019-12-11 06:29:45

问题


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".


回答1:


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



来源:https://stackoverflow.com/questions/19775456/google-apps-script-to-highlight-multiple-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!