问题
I have a find and replace function, it replaces every instance of aa in a string, in VBA it would be xlPart
Is there a way to set the function so that it replaces only whole words or in VBA language xlWhole
Thanks
function FindReplaceWSHT(){
replaceInSheet("Elements",'aa','ZZZ');
}
function replaceInSheet(shtName, to_replace, replace_with) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName);
//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);
}
回答1:
Google Apps Script is based on JavaScript, so you could use the regular expression word delimiter \b.
Example:
function test(){
var sheetName = 'Elements';
var to_replace = 'aa';
var replace_with = 'ZZZZ';
replaceInSheet(sheetName,to_replace,replace_with);
}
function replaceInSheet(sheetName,to_replace,replace_with){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var range = sheet.getDataRange();
var values = range.getValues();
var output = [];
for(var row in values){
output.push([]);
for(var col in values[row]){
var value = values[row][col]
.replace(new RegExp('\\b'+to_replace+'\\b','g'),replace_with);
output[row].push(value);
}
}
range.setValues(output);
}
Test
Input
| A
--+----------
1 |aa
2 |bb aa ccZ
3 |aabbccZ
4 |bbaacc aa
5 |aaaaaaa
Output
| A
--+-------------
1 |ZZZZ
2 |bb ZZZZ ccZ
3 |aabbccZ
4 |bbaacc ZZZZ
5 |aaaaaaa
来源:https://stackoverflow.com/questions/48068218/limit-find-and-replace-to-whole-words-google-sheets-gs-function