如果var为空,则替换文本

时间:2018-03-21 02:06:40

标签: google-apps-script google-sheets google-form

我在用户提交表单时发送电子邮件。这是完美的工作,但我现在想检查变量是否为空(用户没有填充该表单的答案)并根据结果对其执行某些操作。

示例

填充的otherPics变量如下所示:

http://google-drive-link-1

http://google-drive-link-1, http://google-drive-link-2, ...

我想检查变量otherPics是否为空。如果是,我想用字符串"n/a"替换它,如果它不为空,我想用,替换<br>

CODE

function sendEmailNoti(e) {
   var timeStamp = e.namedValues["Timestamp"];
   var qType = e.namedValues["Query Type"];
   var engEmail = e.namedValues["Email address"];
   var jID = e.namedValues["ID"];
   var DataPic = e.namedValues["Data Image"];
   var otherPics = e.namedValues["Other Images"];
   var QueryDesc = e.namedValues["Query"];


if (Object.getOwnPropertyNames(otherPics).length === 0) {
 otherPics = "n/a";  //var is empty
}
else {
 otherPics.replaceText(", ","<br>"); //var is not empty
}

   var subject =  jID + " - " + qType;
   var email = "email@example.com";
   var message = 
    "<strong>" + "EngEmail: " + "</strong><br>" + engEmail + "<br><br>" + 
    "<strong>" + "Timestamp" + "</strong><br>" + timeStamp + "<br><br>" + 
    "<strong>" + "Query Type" + "</strong><br>" + qType + "<br><br>" + 
    "<strong>" + "ID" + "</strong><br>" + jID + "<br><br>" + 
    "<strong>" + "Data Image" + "</strong><br>" + DataPic + "<br><br>" + 
    "<strong>" + "Additional Images" + "</strong><br>" + otherPics + "<br><br>" + 
    "<strong>" + "Query" + "</strong><br>" + QueryDesc + "<br><br>" +
    "<br><br><i>foo bar</i>";

    MailApp.sendEmail({
     to: email,
     replyTo: engEmail,
     subject: subject,
     htmlBody: message
   });
}

1 个答案:

答案 0 :(得分:1)

您可以使用条件(三元)运算符,如下所示:

variablename =(条件)? value1:value2

var otherPics =(e.namedValues [“其他图片”])? e.namedValues [“其他图像”]:“不适用”