Wildcard string comparison in Javascript

后端 未结 7 2155
花落未央
花落未央 2020-12-01 06:00

Let\'s say I have an array with many Strings Called \"birdBlue\", \"birdRed\" and some other animals like \"pig1\", \"pig2\"

7条回答
  •  失恋的感觉
    2020-12-01 06:40

    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);

提交回复
热议问题