-1

I would like to be able to catch strings like:

user input into search field:

Grey box

And in a list there should be a match with:

Grey Boxing Gloves
Grey Window Box
Box with Grey Paint

This should not match:

Greater boxing gloves

Attempts:

(?=.*\b\w*\b).+

Joel
  • 5,732
  • 4
  • 37
  • 65

1 Answers1

0

One way could be using positive lookaheads. They don't consume characters, hence order doesn't matter. If query being searched is Grey box regex will look like:

^(?=.*Grey)(?=.*box)

I wrote a code snippet to build a regex regardless of number of words within it. But take care, query should pass a filtering / quoting process before being used in a regex:

var query = "Grey box";

var list = ['Grey Boxing Gloves',
'Grey Window Box',
'Box with Grey Paint',
'Greater boxing gloves']

// You should filter `query` before building regex
var re = '^(?=.*' + query.split(/\s+/).join(')(?=.*') + ')';

list.forEach(function(x){
   if (x.match(new RegExp(re, 'i'))) {
      console.log(x);
   }
})
revo
  • 47,783
  • 14
  • 74
  • 117