Is there a way to check for a word within cell?

2019-08-18 07:32发布

I am looking for a way to check if a cell contains text in Google Apps Script and Google Sheets.

var cell = "Joe, Bob, Tim, John"

//I would want this to execute
if(cell contains "Tim") {
//code
}

1条回答
你好瞎i
2楼-- · 2019-08-18 08:18

Recently, a TextFinder class was has been added to the SpreadsheetApp service that allows you to do this on a live Range (or Sheet or even a Spreadsheet itself). See documentation for more details. Simply set the finder on a context with a createTextFinder() with the text you want to find as an argument. Calling a findNext() method on the resulting TextFinder instance will either return the Range it was called on or null if nothing was found. For example:

function findText() {

  var sh = getSheet(); //custom function that returns target Sheet;
  var rng = sh.getRange(1,1); //change to desired Range boundaries;

  //create TextFinder and configure;
  var tf = rng.createTextFinder('textToFind');
      tf.matchCase(false); //{Boolean} -> match target text's case or not;
      tf.matchEntireCell(false); //{Boolean} -> check the whole Range or within;
      tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
      tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

  //invoke search;
  var res = tf.findNext();

  //do something with result;
  if(res!==null) {
    var vals = res.getValues();
    Logger.log(vals);
  }

}
查看更多
登录 后发表回答