Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-forms

Apps Script - splitting google form checkbox answers by commas


Google form checkbox question combines the selected responses into one column separated by commas. I am trying to send out a confirmation email of these responses, but the email results in a clunk format:

Register: 9:15 AM - 10:00 AM Instructional Technology Tools & Resources (electronic lab notebooks, classroom tech, analytics, etc.), 10:10 AM - 11:00 AM Tools for flipped or hybrid (blended) courses (learning glass, instructional design, Ted, podcast, etc.)

I'd like to replace the comma separator with <br> but haven't been able to figure it out.

I've tried:

register = e.namedValues[headers[4]].split(',');


register = e.namedValues[headers[4]];
workshops = register.replace(",", "<br>");

Any help would be greatly appreciated! Thank you!

for (var i in headers) {
  ....... ....... 
  register = e.namedValues[headers[4]];
} 

if (e.namedValues[headers[i]].toString() != "" ) {
  textbody = ....... + register + "<br>"
}

Solution

  • Should be structured like this:

    for (var i in headers) {
      ....... ....... 
      register = e.namedValues[headers[i]].toString();
    
      if (register != "" ) {
        textbody = register.replace(/,/g, "<br>");
      }
    }
    

    You need to perform a global replacement, after converting the array to a string.

    function replaceCommas() {
      var headers = ['First Name', 'Timestamp', 'Last Name', 'workshops'];
      var register = {'First Name': ['Jane', 'Jon', 'Jim', 'Josie'], 'Timestamp': ['6/7/2015 20:54:13'], 'Last Name': ['Doe'], 'workshops': ['learning glass', 'instructional design', 'Ted', 'podcast']};
    
      //register = e.namedValues[headers[4]].split(',');
    
      var keyName = headers[3]; //Arrays are Zero indexed, fourth item is index 3
      Logger.log('keyName is: ' + keyName);
    
      var stringOfValues = register[keyName].toString();
      Logger.log('stringOfValues: ' + stringOfValues);
    
      var workshops = stringOfValues.replace(/,/g, "<br>");
    
      Logger.log('workshops: ' + workshops);
    }
    

    Copy the above function into your script editor, set a breakpoint on something like the first Logger.log() statement, and step into each line. You can see all the values of the variables in the debug window at the bottom of the screen.

    To set a breakpoint, click a line number, and a red dot will appear, that's where the code will stop. Then click the icon of the bug. The code will run up to the point of the breakpoint.

    Here is a link to the debug documentation:

    Google Documentation - Troubleshooting