I want a find/replace script in Google Sheets App script using RegEx to find and replace over multiple columns. I can only either find and replace using RegEx in one column or find and replace over multiple columns but don't seem to be able to use RegEx. Any ideas?
Here are those two scripts:
Finds and replaces using RegEx but will only work in 1 column:
var sheet = SpreadsheetApp.getActiveSpreadsheet()
var range = sheet.getRange("D:D");
range.setValues(range.getValues().map(function(row) {
return [row[0].replace(/\".*$/, "")];
}));
Finds and replaces plain text over multiple columns:
var to_replace = "example text"
var replace_with = "";
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('examplesheet');
var lastRow = sheet.getLastRow();
var ranges = ['E2:Z' + lastRow];
sheet.getRangeList(ranges).getRanges().forEach(r =>
r.createTextFinder(to_replace).replaceAllWith(replace_with)
);
I'm not sure, but if your range is made of lines and columns, then you'll have to do 2 levels of
map()calls, in order to loop over rows and then loop over cells in each row.I tried this and it worked for me:
In this example, I used a regex with capturing groups and with a callback function instead of a replacement string. This was to show that one can do quite complex replacements if needed.