Google Apps Script:如何将表单获取的邮箱对象转为字符串?
Fixing Email String Conversion in Google Apps Script for Form Submissions
Hey there! Let's get this sorted out for you. The issue here is that e.namedValues["Email address"] doesn't return a single string—it actually returns an array (even if only one email is submitted, Google Forms wraps it in an array). That's why calling .replace() directly on studentID throws an error, because arrays don't have that method.
Here's the corrected code:
First, fix the variable name typo in your loop (keys → key), then extract the first element from the array and ensure it's a string:
for (var key in columns) { if (key === "Email address") { // Pull the first (and only) email from the array, convert to string var studentEmail = e.namedValues[key][0].toString(); var theEmail = studentEmail.replace(/@.*/, ""); // Now theEmail holds the username before the @ symbol } }
Why this works:
e.namedValues[key]returns an array of responses for that field. Since your email field is a single input,[0]grabs the only entry..toString()explicitly converts the value to a string (though in most cases, the array element will already be a string—this adds a safety net).- We also fixed the loop variable mismatch (
keysvskey) which would have caused your condition to fail.
Even simpler: Skip the loop
If you know the exact field name ("Email address"), you can access it directly without looping through columns:
var studentEmail = e.namedValues["Email address"][0]; var theEmail = studentEmail.replace(/@.*/, "");
This is more efficient and avoids any loop-related mistakes.
内容的提问来源于stack exchange,提问作者Carl Arrowsmith
相关产品推荐
相关产品推荐

