I've been trying to work on replacing some text within a Google script but it's not producing what I'd like. At present I am using Cameron Roberts' script from here - How do I replace text in a spreadsheet with Google Apps Script? to make my replacements however I've not got it quite right.
Using that code I am trying to replace the word 'values' with '1. values' however if I run the code multiple times it produces '1. 1. values' etc as it just finds the 'values' string. What I'd like is a wildcard which just searches for 'values' and then puts '1. values' in but I can't seem to grasp the regular expression syntax well enough to fix it.
function testReplaceInSheet(){
var sheet = SpreadsheetApp.getActiveSheet()
replaceInSheet(sheet,'values','1. values');
}
function replaceInSheet(sheet, to_replace, replace_with) {
//get the current data range values as an array
var values = sheet.getDataRange().getValues();
//loop over the rows in the array
for(var row in values){
//use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = values[row].map(function(original_value){
return original_value.toString().replace(to_replace,replace_with);
});
//replace the original row values with the replaced values
values[row] = replaced_values;
}
//write the updated values to the sheet
sheet.getDataRange().setValues(values);
}