问题
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 modifyreturn val[C2] == "*Y";
toreturn /abc$/.test(val[C2]);
andreturn val[C2].slice(-3) === "abc";
. - When you want to retrieve the element which includes
cde
in the value,. please modifyreturn val[C2] == "*Y";
toreturn 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