We need capture group of regex for properly capturing all cases, not just words between spaces. (e.g. ms. “ms” ms, ms! ms? ms! ‘ms’)
But since replaceText
doesnt support capture group while replace
does, we need to derive it using replace
inside replaceText
.
EDIT:
Code:
function replMyText() {
var ss = SpreadsheetApp.openById('1-WblrS95VqsM5eRFkWGIHrOm_wGIPL3QnPyxN_j5cOo');
var sh = ss.getSheetByName('find and replace');
var doc = DocumentApp.getActiveDocument();
var rgtxt = doc.getBody();
var rgrep = sh.getRange('A2:C103');
var repA = rgrep.getValues().filter(r => r.every(c => c.toString()));
// Search per paragraph so it won't produce exponential copies per paragraph
var paragraphs = rgtxt.getParagraphs();
for (var i = 0; i < paragraphs.length; i++) {
repA.forEach(function(e){
if(e[2] == "match case") {
DocumentApp.getActiveDocument().getBody().replaceText(e[0], e[1]);
}
else if (e[2] == "exact match") {
// Only replace the string in between non [a-zA-Z0-9_]
// Capture string including 2 \W characters around it, then pad them around the replaced string
var replace = "(\\W)" + e[0] + "(\\W)";
var re = new RegExp(replace, "g");
var text = paragraphs[i].getText();
paragraphs[i].replaceText(".*", text.replace(re, "$1" + e[1] + "$2"));
// Replace the ones starting in a paragraph if present
replace = "^" + e[0] + "(\\W)";
re = new RegExp(replace, "g");
text = paragraphs[i].getText();
paragraphs[i].replaceText(".*", text.replace(re, e[1] + "$1"));
}
});
}
}
Latest update tests:

Latest update output:

References: