que syrah sarah
que syrah sarah

Reputation: 231

Google Sheets Script - find/replace - find lower and uppercase words, exact match

I am using a script that finds/replaces words onEdit. However, it does not work on words that are capitalized (my find query is lower case). How can I get it to match both the upper and lowercase words that are an exact match?

Example: find: "sun" and "Sun" replace: "sunshine" (lowercase only)

Also, I do NOT want it to replace partial words Example: find: "sun" and "Sun" exact string -- not "sunny" or "sung" or "sundry"

Appreciate any help you can provide!

My script:

function onEdit(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("pss");
  var lr = ss.getLastRow();
  var range = ss.getRange("A2:J" + lr);
  var vlst = range.getValues();

  range.setValues(vlst);
  var i,j,a,find,repl;
   for (var i = 0; i < vlst.length; i++){
    for (var j = 0; j < vlst[i].length; j++){
      a = vlst[i][j];
      if (a == find) vlst[i][j] = repl; 
    find ="sun";
    repl ="sunshine";
    }
  }

Upvotes: 1

Views: 1024

Answers (1)

TheMaster
TheMaster

Reputation: 50501

Issues:

  • Improper ordering of statements &syntax:
    • setValues() should be used after replacing all values(NOT before).
    • find/repl variables should be declared and initialized before the if statement(Though it works for subsequent loops due to hoisting/scoping).
    • Missing }
  • Case Insensitive find and replace

Solution:

  • Reorder and initialize variables before execution.
  • Use objects¹ to store key/value pairs.
  • Use toLowerCase()² on find variable.
  • Alternatively, use event objects³ instead of looping through everything.

Modified Script:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("pss");
  var lr = ss.getLastRow();
  var range = ss.getRange("A2:J" + lr);
  var vlst = range.getValues();
  var findReplace = { //FindReplace object storing key/value pairs in lowercase
    'sun': 'sunshine',
    'moon': 'moonlight',
    'evil': 'evil MasterMind'
  };
  var i, j, a;
  for (i = 0; i < vlst.length; i++) {
    for (j = 0; j < vlst[i].length; j++) {
      a = vlst[i][j].toString().toLowerCase();
      if (findReplace[a]) vlst[i][j] = findReplace[a];
    }
  }

  range.setValues(vlst); //Moved below
}//Added

Script#2

function onEdit(e) {
  var findReplace = {
    'sun': 'sunshine',
    'moon': 'moonlight',
    'evil': 'evil MasterMind'
  },
    a = findReplace[e.value.toString().toLowerCase()];
  if (a) e.range.setValue(a);
}

Upvotes: 1

Related Questions