Google App Script regex replace for multiple values not working with single quote

一世执手 提交于 2020-03-05 00:27:14

问题


Problem

Using the below code i'd like to replace all "'NULL'" values to "NULL". Currently it will only replace one value.

Code

function generateSQLCode() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('seed-data');
  var row_count = sheet.getLastRow();
  var input_data = sheet.getRange(1, 1, row_count, 20).getValues();
  var data = [];

  for (var i = 0; i < row_count; i++) {

      var row_data; 

      } else if (input_data[i][0] == "entry") {
        row_data = input_data[i].shift();
        row_data = "('" + input_data[i].filter(e=> e!=="").join("', '").replace(/'NULL'/gi, "NULL") + "');";


      data.push([row_data]);
  }
  sheet.getRange(1, 21, data.length, 1).setValues(data);
}

Data

previous_version_id   dev_id    build_number                                            
NULL                  1         NULL

回答1:


Had to reassign row_data to get the full string before replacing any NULL values.

else if (input_data[i][0] == "entry") {
row_data = input_data[i].shift();
row_data = "('" + input_data[i].filter(e=> e!=="").join("', '") + "'),";
row_data = row_data.replace(/'NULL'/gi, "NULL")



回答2:


Instead of itereating for all the array that could be very time consuming let me recommend you a nice class built in Apps script called TxtFinder.

That could simplify a lot of your code and make it faster.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  Logger.log(sheet.getName());
  var range = sheet.getDataRange();


  var txtFinder = range.createTextFinder("'NULL'");
  txtFinder.replaceAllWith("NULL")


}

Try using this snippet and see how it goes.

Explanation

To use the TxtFinder class you first need to create an object, you can do with the method createTextFinder.

You can actually use this method not only for a range, like I did but for the sheet or even the whole spreadsheet.

After having this object created (txtFinder in my example). You can do a lot of stuff listed in the TxtFinder class. For your case just use replaceAllWith(), to replace all the matches.


Also notice that if you want to look for all the data in your sheet, you can simply call getDataRange()



来源:https://stackoverflow.com/questions/60173693/google-app-script-regex-replace-for-multiple-values-not-working-with-single-quot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!