Home > Blockchain >  Replace multiple words with only one word in googlesheets with apps script
Replace multiple words with only one word in googlesheets with apps script

Time:08-31

I have a Google sheets with texts in 590 rows. I need to replace multiple words of these texts in other word as a category. For example, I need to find the words "brontolaren minacciaren pettegolezzin maleducaton" and replace them with the word "relazionin". I'm trying to write an apps scripts to do this, and I found a script created by FluffyLlemon that I adapted, and I thought could work for me:

  function FindAndReplace() {
  var data_range = SpreadsheetApp.getActiveSheet().getDataRange();  
  var num_rows = data_range.getNumRows();
  var num_columns = data_range.getNumColumns();
  

  var find_replace ={
     "brontolaren" : "relazionen", 
     "minacciaren" : "relazionen", 
     "pettegolezzin" : "relazionen",
     "maleducaton" : "relazionen", 
     "riservatezzan" : "relazionen", 
     "sottopressionen": "relazionen",
     }

    Object.keys(find_replace).map(function(find) {
    var replace = find_replace[find];
    for (var row=1; row <= num_rows; row  ) {
     for (var col=1; col <= num_columns; col  ) {
        var value = data_range.getCell(row, col).getValue();
        if (data_range.getCell(row, col).getFormula()) {continue;}
        try {
           value = value.replace(find, replace);
           data_range.getCell(row, col).setValue(value);
        }
        catch (err) {continue;}
     }
  }
 });
}

By executing this code, just the first word is replaced and not the others, and it seems to take a long time and never stop. This is the first time I use apps script... How can I improve the code?

CodePudding user response:

Try it this way:

function FindAndReplace() {
  const ss = SpreadsheetApp.getActive();
  var rg = ss.getDataRange();  
  const r = "relazionen";
  const f =["brontolaren","minacciaren","pettegolezzin","maleducaton","riservatezzan","sottopressionen"];
  f.forEach(n => {
    rg.createTextFinder(n).replaceAllWith(r);
  });
}
  • Related