Here you may see samples of code I've developed and maintain in GitHub for GAS and other languages as well as my code donations to open source communities. I maintain all these code samples as MIT/X11 Licensed as I welcome open source development but wish to ensure proper disclaimers. I believe that through open source we can develop bigger, innovative, transcendental ideas by sharing items from small AddOns to full development code.
For accessing my GitHub samples, please visit my repository @ https://github.com/sayuga
Google App Script
Advanced Replace Text
Example: advReplaceText("mergeThis", "_Field", "{placeHolder1}", "01234567890");
/**
* Merges data into the google doc by matching the tag.
* Uses the 'type' designation to properly manage merge behavior.
*
* @param {object} data Data being merged. Can be string, numbder, boolean, blob, etc.
* @param {object} dataType Designates handler for the data being merged.
* @param {object} tag Placeholder identifier within document to be merged into.
* @param {string} docId Google ID of new report
*/
function advReplaceText(data, dataType, tag, docId){
var newDoc = DocumentApp.openById(docId);
var newBody = newDoc.getBody();
var style = {};
style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.CENTER;
var currentData = (data != undefined)?(data!=null)?data:null:null;
while (isNullUndefined(newBody.findText(tag)) == false){ //Merges tag until no more matches found
if (currentData == null){ //if data is a blank just clear tag.
newBody.replaceText(tag, "");
}
else{
switch(dataType){
case "_Chart":
var blob = currentData; //Extracts chart blob
var replacedParent = newBody.findText(tag).getElement().getParent().asParagraph(); //gets tag location
var clearTag = newBody.replaceText(tag, ""); //removes tag
var cImg = replacedParent.appendInlineImage(blob).setAttributes(style); //adds chart at tag location using set "style"
cImg.setHeight(250).setWidth(600);
break;
case "_Image":
var blob = DriveApp.getFileById(currentData).getBlob(); //gets image blob from GID
var replacedParent = newBody.findText(tag).getElement().getParent().asParagraph(); //gets tag location
var clearTag = newBody.replaceText(tag, ""); //removes tag
var cImg = replacedParent.appendInlineImage(blob).setAttributes(style); //adds image at tag location using set "style"
cImg.setHeight(250);
break;
case "_Field":
newBody.replaceText(tag, currentData); //Replaces tag with value
break;
default:{
newBody.replaceText(tag, ""); //when in doubt, remove the tag.
break;
}
}
}
}
newDoc.saveAndClose();
};
IsNullUndefined Checker
/**
* Checks if given value is Null, undefined or "".
*
* @param {object} val Value being checked
*/
function isNullUndefined(val){
var result = false;
switch (val){
case null:
result = true;
break;
case undefined:
result = true;
break;
case "":
result = true;
break
default:
result = false;
break;
}
return result;
};
Other Samples