Search code examples
google-apps-scriptmatchpartial

Partial match of strings for filter method in Google Sheet GAS


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'


Solution

    • 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:

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