Let\'s say I have an array with many Strings Called \"birdBlue\"
, \"birdRed\"
and some other animals like \"pig1\"
, \"pig2\"
This function convert wildcard to regexp and make test (it supports .
and *
wildcharts)
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\\]/g, '\\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
// Example usage
let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];
let resultA = arr.filter( x => wildTest('biRd*', x) );
let resultB = arr.filter( x => wildTest('p?g?z', x) );
let resultC = arr.filter( x => wildTest('*Blu?', x) );
console.log('biRd*',resultA);
console.log('p?g?z',resultB);
console.log('*Blu?',resultC);