Google电子表格搜索部分,替换和删除

时间:2017-11-16 15:15:41

标签: javascript google-apps-script google-sheets

我试图使用Tasker(一个为Android开发的应用程序)开始一个项目它有很多有用的插件,我偶然发现谷歌电子表格插件。 有了这个插件,我可以轻松地从电子表格中读取 但我的问题是写入电子表格。我想将电子表格用作我的任务应用程序的数据库。

这意味着它会将简单值写入电子表格示例
A2 = Nexus5 / off:1:8:1
A3 = Nexus6 / on:2:3:4

我现在正在尝试编写搜索脚本并在google脚本中替换。我被卡住了。
我想要它做的是如果我的Nexus5打开它将发送到A1 Nexus5 / on:1:8:1的电子表格。

脚本必须在 A 列中搜索Nexus5 /,并使用新值替换单元格值。之后它必须删除 A1 ,这样就可以输入新的输入。下面是我到目前为止所获得的脚本,它可以搜索我放入A1的输入,并在列表中用test替换它。但我似乎无法在第一部分进行搜索。

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);
}
function onChange(e){
  var sheet = SpreadsheetApp.getActiveSheet()
  replaceInSheet(sheet,val,'test');
}

1 个答案:

答案 0 :(得分:0)

你想用regexes破解这个坚果。有comprehensive set of answers here

简而言之,将搜索设置为/^Nexus5\//(使用原始正则表达式声明,或creating a new RegExp() object)&只需使用string.replace(),然后根据需要写回更新的值。

e.g。

var myString = “Nexus5/1.2.3”;
var newValue = myString.replace(/^nexus5\/.+/i, “my new value”); 

所以,我们在这里寻找以“Nexus5 /”开头的字符串&用“我的新价值”取而代之。 (^ 锚定搜索到字符串的开头,.+表示除了行尾之外的1个或多个字符,我们需要转义斜杠 - {{1在模式将搜索设置为不区分大小写之后,它不被解释为正则表达式和\/的结尾。)现在我们可以将i写回源表但是您需要使用电子表格的range.setValue()range.setValues()方法。

相关问题