简体   繁体   中英

Script to automatically delete words from google sheet

I have very little coding experience so please bear with me. I am trying to write a script that will check every cell in a google sheet if a cell contains a certain word it will either delete all contents from that cell or preferably will revert the cell back to its previous state before that edit. For example, say I am looking for the word “new” and a cell contains “this is a test sentence” and then is edited to say “this is a test sentence with the word new added” I would want that cell to be cleared or go back to “this is a test sentence”. The code below works, but only if the cell has the exact word in it. So if a cell just contains “new” or “car” it clears the cell, but if the cell contains “new car” nothing happens.

function onEdit(e) {
  return e.value ? (listOfWords(e.value) !== -1 ? e.range.clearContent() : null) : null;  
}

function listOfWords(word) {
  var listEN = ['new','car'];
  return listEN.indexOf(word);
}

Try this:

function onEdit(e) {
  //e.source.toast("Entry");
  const sh = e.range.getSheet();
  Logger.log(JSON.stringify(e));
  if(sh.getName() == "Sheet0") {
    //e.source.toast("If1")
    const list = ["new","car","red","green"];
    const wA = e.value.split(/ /);
    wA.forEach((w,i) => {
      //Logger.log(w)
      e.source.toast("If2")
      let idx = list.indexOf(w);
      if(~idx) {
        //Logger.log('i: %s, word: %s idx: %s',i,w,idx);
        wA.splice(i,1);
        //Logger.log(wA.join(" "));
        e.range.setValue(wA.join(" "))
      }
    })
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM