javascript - 使用 Google App 脚本替换 Google Sheet 中的文本而不重新格式化值

标签 javascript string google-apps-script google-sheets replace

我有一个问题需要帮助。

我正在使用一个函数(我在本网站其他地方找到的)来循环遍历我的电子表格的所有行,以用空格(“”)替换“未定义”一词。

代码工作正常,但由于代码中的 .toString 方法,它似乎也将日期从 mm/dd/yyyy 格式重新格式化为文本字符串。

我不想重新格式化日期(或数字),但我还没有找到一种无需 .toString 方法即可重写代码的方法。

有谁知道我可以替换 Google 表格中的文本而无需先将其格式化为字符串的方法吗?

这是下面的代码。我很感谢对此的任何帮助。

function replaceInSheet(sheet, to_replace, replace_with) {

  var Data = SpreadsheetApp.getActiveSpreadsheet(); // DATA spreadsheet
  //get the current data range values as an array
  var values = Data.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("undefined","");
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }

  //write the updated values to the sheet
  Data.getDataRange().setValues(values);
}

最佳答案

  • 您想要使用 Google Apps 脚本将电子表格单元格的 "undefined" 字符串替换为 ""
  • 您不想影响没有“未定义”值的单元格

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

例如,作为多种解决方法之一,使用 TextFinder 怎么样?使用 TextFinder 时,没有“undefined”值的单元格不受影响。在这种情况下,请按如下方式修改您的脚本。

修改后的脚本:

function replaceInSheet(sheet, to_replace, replace_with) {
  var Data = SpreadsheetApp.getActiveSpreadsheet();
  Data.getDataRange().createTextFinder("undefined").replaceAllWith("");
}

引用文献:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

关于javascript - 使用 Google App 脚本替换 Google Sheet 中的文本而不重新格式化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59905025/

相关文章:

javascript - 人们可以查看您的 js 文件通常安全吗

javascript - jQuery 边距取决于元素宽度

google-apps-script - 如何在 Google 电子表格中使用 ImportRange 函数强制重新计算单元格?

javascript - 如何使用 jquery 动态地将文本从文本框放入 div 内的标签

javascript - 在新选项卡中打开链接在 IE10 中不起作用

c - 如何在 C 中的用户定义后在程序中 append 文件名

python - 我可以在 python3 中使 pprint 不拆分字符串,就像在 python2 中一样吗?

java - JSoup:从类标签中提取一个词

google-apps-script - 如何为 Google 表单生成预先填写的表单 URL

google-apps-script - 使用 Google Apps 脚本删除 Google 文档中的表格行