问题
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