使用Google表单填充Google文档:表单空字段引发标点异常问题
Fixing Extra Commas in Google Apps Script for Signature Collection
Hey Dylan, let's sort out that annoying extra comma problem in your script! Right now, you're hardcoding commas between every field—even when some are empty—which is why you're getting messy outputs like Bob, , when title and affiliation are blank. Here's a clean, robust way to handle this by only including non-empty values in your final string:
Modified Script
function appendSignatureRow(e){ const lock = LockService.getScriptLock(); lock.waitLock(30000); const name = e.values[2]; const title = e.values[3]; const affiliation = e.values[4]; // Create an array to hold only non-empty values const signatureParts = []; // Add name (required, so it will always be present) signatureParts.push(name); // Add title only if it's not empty (and not just whitespace) if (title && title.trim() !== "") { signatureParts.push(title); } // Add affiliation only if it's not empty (and not just whitespace) if (affiliation && affiliation.trim() !== "") { signatureParts.push(affiliation); } // Join the valid parts with ", " to avoid extra commas const sig = signatureParts.join(', '); const letter = DocumentApp.openById('DOC_ID_IS_HERE'); const body = letter.getBody(); body.appendParagraph(sig); letter.saveAndClose(); lock.releaseLock(); }
How This Works
- Array for Valid Values: We use an array
signaturePartsto collect only fields that have actual content. Since name is required, we add it first without checking. - Empty Field Checks: For title and affiliation, we check if the value exists and isn't just whitespace (using
trim()to catch accidental space inputs). If it's valid, we add it to the array. - Smart Joining: The
join(', ')method takes all elements in the array and puts them together with ", " between each one. This automatically handles every scenario you need:- No extra commas when both optional fields are empty (outputs just
Bob) - Correct comma placement when one optional field is filled (e.g.,
Bob, Universitywhen title is blank) - Proper formatting when all fields are provided (e.g.,
Bob, Professor, Stanford University)
- No extra commas when both optional fields are empty (outputs just
This approach is also flexible—if you ever add more optional fields later, you just repeat the check-and-push pattern for the new field, and the join method will handle the rest!
内容的提问来源于stack exchange,提问作者Dylan Siegel
相关产品推荐
相关产品推荐

