Home > Enterprise >  RegEx matching problem with array.indexOf() in Google Scripts
RegEx matching problem with array.indexOf() in Google Scripts

Time:10-22

I can't get IndexOf to match correctly in GAS

I've tested out my regular expression here: https://regex101.com/r/0cK6xQ/1

As soon as there is a space inside the string, indexOf() will not match. I even tried setting the regex as let contactRegExp = /(contact 1 Type)/i ; , which should be a direct match for the 2nd element in the sample array and it bombs out.

function setContactTypes(){  

 //Find all contact Type columns
 let contactRegExp = /(contact [\d]* Type)/i ;

 var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];

 var hitArray = [];
 var i = -1;
 while ((i = headerIndexList.indexOf(contactRegExp,(i 1))) != -1){
     hitArray.push(i);
  }
}

hitArray should return [1,3]

I'm thinking it has something to do with an Array vs a string, but for the life of me can't figure it out.

CodePudding user response:

Unfortunately, Array.prototype.indexOf() cannot use the regex. So in your situation, in order to achieve your goal, how about the following modified script?

Modified script:

function setContactTypes(){  
 let contactRegExp = /(contact [\d]* Type)/i ;
 var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];
 var hitArray = headerIndexList.reduce((ar, e, i) => {
   if (contactRegExp.test(e)) ar.push(i);
   return ar;
  }, []);
  console.log(hitArray) // When your "headerIndexList" is used, [1, 3] is returned.
}

Testing:

Show code snippet

let contactRegExp = /(contact [\d]* Type)/i ;
var headerIndexList = ['dummy1','contact 1 Type','dummy2','contact 2 Type'];
var hitArray = headerIndexList.reduce((ar, e, i) => {
  if (contactRegExp.test(e)) ar.push(i);
  return ar;
}, []);
console.log(hitArray)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

References:

Added:

For example, the following script is useful for your situation?

let contactRegExp = /(contact [\d]* Type)/i;
var headerIndexList = ['dummy1', 'contact 1 Type', 'dummy2', 'contact 2 Type'];
var hitArray = [];
for (var i = 0; i < headerIndexList.length; i  ) {
  if (contactRegExp.test(headerIndexList[i])) {
    hitArray.push(i);
  }
}
console.log(hitArray)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related