5th4x4
5th4x4

Reputation: 1577

Search / Find text for an if statement

What I am trying to do is very simple. Unfortunately I can't seem to get it to work in gas. I'll now embarrass myself and post my latest (of many!) attempts:

      var ss = SpreadsheetApp.getActiveSpreadsheet(); // 
      var findVal = ss.getRange("A1").getValue()
      if (findVal.findText("8762", "#N/A"));
      { 
        // do something
      }
      else {
        // do something else
      }

I'm just looking to search in a specific cell for the existence of either the number 8762 among a large paragraph of text, or the string #N/A, which will be the only text in the cell. (FYI: the #N/A is not the result of a formula. It's actual text).

And obviously I'm trying to use the result of that "find" as the driver for a conditional statement.

I'm not a dolt in a VBA world, but javascript in a spreadsheet setting can make me feel very foolish at times. Such as right now.

Btw, I did do extensive searching for this solution. Unfortunately everything that I found was part of large convoluted exercises that muddied the waters for me. I just need a basic true/false solution and nothing more.

And yes, I can do the easy half of that...

    var ss = SpreadsheetApp.getActiveSpreadsheet(); // 
    var findVal = ss.getRange("A1").getValue()

     if (findVal == "#N/A") { 

   // do something

  }

  else {

   // do something else

}

(just to prove that I'm not here looking for a handout... only a helping hand)

Upvotes: 2

Views: 9047

Answers (1)

Henrique G. Abreu
Henrique G. Abreu

Reputation: 17792

Nice attempts. It's great to see what you're trying. I think what you're looking for is the String match function. This is not specific to Apps Script, therefore you'll not find it in its documentation, but rather on generic javascript docs, e.g. on MDN.

if( findVal.match('8762') || findVal == '#N/A' ) {
  //do something
} else {
  //do something else
}

Note that even though we passed a string as a parameter for the match function, it is converted into a regular expression. So, it's good you give it a quick study. It may look too complicated but is very useful and rather simple once you get a hold of it.

Another way of doing the above:

if( findVal.match(/8762|^#N\/A$/) ) {

And even better, we can guarantee that your number is "alone" and not part of a larger number, as in 187621.

if( findVal.match(/\b8762\b|^#N\/A$/) ) {

Upvotes: 6

Related Questions