Javascript 将查找和替换限制为整词googlesheets.gs函数
我有一个查找和替换函数,它在字符串中替换Javascript 将查找和替换限制为整词googlesheets.gs函数,javascript,regex,google-apps-script,google-sheets,Javascript,Regex,Google Apps Script,Google Sheets,我有一个查找和替换函数,它在字符串中替换aa的每个实例,在VBA中则是xlPart 是否有办法设置该函数,使其仅替换整词或VBA语言中的xlother 谢谢 function FindReplaceWSHT(){ replaceInSheet("Elements",'aa','ZZZ'); } function replaceInSheet(shtName, to_replace, replace_with) { var sheet = SpreadsheetApp.getActiv
aa
的每个实例,在VBA中则是xlPart
是否有办法设置该函数,使其仅替换整词或VBA语言中的xlother
谢谢
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);
}
GoogleApps脚本基于JavaScript,因此可以使用正则表达式单词分隔符\b
例如:
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);
}
试验
输入
| A
--+----------
1 | aa
2 | bb aa ccZ
3 | aabbccZ
4 | bbaacc aa
5 | AAAAA
输出
| A
--+-------------
1 | ZZZZ
2 | bb ZZZZ ccZ
3 | aabbccZ
4 | bbaacc ZZZZ
5 | AAAAA
在搜索词前后添加空格不起作用?我想在VBA中会有一种更正式的方法来实现这一点,不太容易出错。另外,如果搜索词是整个单元格内容,也是一个子字符串,那么如何做到这一点呢?因为gs是从javascript构建的,而ht eonly replace函数就是js。你可以看看这个:鲁本,谢谢你,有没有办法让它只在整词上匹配
,因为它取代了子字符串,即aaa>>ZZZa我只想要整词aa>>ZZZ@Tim当前位置对我来说很好。我在答案中添加了输入/输出验证数据。考虑更新你的问题显示你的适应。如果单元格中的第一个
字或单元格只有一个
字,然后,如果aa
是单词的子字符串,那么aa
会变成ZZZZ
例如aaee
那么我会得到ZZZZee
,否则works@Timaaee
相当于aabbccZ
和我做的测试中的aaaaaaaa
。你对我的密码做了任何修改吗?你能创建一个演示电子表格并分享它吗?鲁本,我关闭了然后重新打开了我的GS文件,知道一切正常!再次感谢你的帮助