【发布时间】:2016-11-21 15:11:49
【问题描述】:
我一直在尝试替换 Google 脚本中的一些文本,但它没有产生我想要的结果。目前我正在使用来自这里的 Cameron Roberts 的脚本 - How do I replace text in a spreadsheet with Google Apps Script? 进行替换,但是我没有完全正确。
使用该代码,我试图用“1”替换“值”这个词。 values' 但是,如果我多次运行代码,它会产生 '1. 1. values'等,因为它只是找到'values'字符串。我想要的是一个通配符,它只搜索'values',然后输入'1。 values' in,但我似乎无法很好地掌握正则表达式语法来修复它。
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);
}
【问题讨论】:
-
好吧,
1. values包含values,所以它需要离开1. <replace with>,这将是1. 1. values。你希望它发生什么?什么都不做? -
感谢您的回复。我想用“1”替换“值”。值',但显然每次运行时,正如你所说,我会得到一个额外的'1。 '前缀。我想我想要的是包含'values'的整个字符串被替换为只显示'1。价值观”。
标签: google-apps-script google-sheets