0

I want to test if any string in an array matchs with a particular string. However, the strings in array may contain the asterisks pattern.

var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*foo"];
var toMatch = "foo_1";

For this sample, the result will be true because foo_*, *foo_1 and foo_1* will match with foo_1, but bar and *foo won't.

I have tried to use split function with lodash _.some but it seems overcomplicated and I can't make it works consistently.

function isMatching() {
    return _.some(toTest , function(a) {
        return _.some(a.split("*"), function(part1, idx1) {
            return (part1.length && _.some(toMatch.split(part1), function(part2, idx2) {
                return (part2.length && idx1 == idx2);
            }));
        });
    });
}
Below the Radar
  • 7,321
  • 11
  • 63
  • 142

1 Answers1

2

To achieve expected result, use below option of using filter, indexOf and replace

var toTest = ["foo_*", "*foo_1", "foo_1*", "bar", "*_foo"];
var toMatch = "foo_1";

console.log(toTest.filter(v => toMatch.indexOf(v.replace('*', '')) !== -1))
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40