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

replaceText Google Apps Script pass through blank values to Google Doc Merge


I'm doing something like a mail merge - taking values from google sheets (actually script array) and replacing placeholder variables in a google doc template. I have about 50 of these. Below are three of them. The format looks like this:

body.replaceText("{Property Address}", propertyAddress);
body.replaceText("{Lead Type}", leadType);
body.replaceText("{Deal Type}", dealType);

The problem I'm running into is sometimes a variable can be blank - e.g. say leadType is blank or "". There is an error occurring if it's blank. What I want to do is if leadType has a value, then replace {Lead Type} in the Google Doc with the value. Else if leadType = null or "" or undefined etc., then replace {Lead Type} in the Google Doc with "". I'd rather not have to do an if/then statement for each of these 50 lines. Is there an easy way to have either a value or a blank push through to the sheet (I want a blank to go through because I don't want the final sheet to be printed with {} variables)


Solution

  • How about using the OR operator?

    body.replaceText("{Property Address}", propertyAddress || "");
    body.replaceText("{Lead Type}", leadType || "");
    body.replaceText("{Deal Type}", dealType || "");