Partial match of strings for filter method in Google Sheet GAS

混江龙づ霸主 提交于 2019-12-25 01:48:57

问题


I have the following codes:

var filteredRange = rangeVals.filter(function(val){
    return val[C2] == "ANTHONY";
    });

This code works fine for an exact match. But if I would like to look for any values that ends with Y, this does not return anything:

  var filteredRange = rangeVals.filter(function(val){
    return val[C2] == "*Y";
    });

I have tried to us wildcard "%Y" but apparently this is not the correct way either. I have tried to look into this resource of RegExp from MDN but I can't seem to integrate the information for this purpose. I have read a lot of different posts here but none seem to address what I need so far. Can someone point me in the right direction? I am interested in knowing how to retrieve values that match based on a partial match, e.g. beginning with a letter, or ending with a letter, or containing string like 'cde' in 'abcdefg'


回答1:


  • You want to retrieve the element, which has Y at the last character, from the 2 dimensional array using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modified script:

From:
return val[C2] == "*Y";
To:
return val[C2].slice(-1) == "Y";

or

return val[C2][val[C2].length - 1] == "Y";

or

return /Y$/.test(val[C2]); // regex is used.

Note:

  • When you want to retrieve the element which has abc at the last character, please modify return val[C2] == "*Y"; to return /abc$/.test(val[C2]); and return val[C2].slice(-3) === "abc";.
  • When you want to retrieve the element which includes cde in the value,. please modify return val[C2] == "*Y"; to return val[C2].indexOf("cde") > -1;.

References:

  • slice()
  • test()
  • indexOf()

If I misunderstood your question and this was not the result you want, I apologize.



来源:https://stackoverflow.com/questions/58884413/partial-match-of-strings-for-filter-method-in-google-sheet-gas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!