0

I have an autocomplete that has multiple categories with values that matches any set of letters from the users input. Each category value has multiple strings stored in it (see value.application sample data below).

This works fine, but I want it to only match entire words intead of letter combination. How can this be achieved?

Example:

Source Data: "all caller tallest"

User Enters: "all"

Returns: "all caller tallest"

Looking for it to only return: "all"

source: function(request, response) {
  var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); // match letters in string

  response($.grep(SearchList, function(value) {
  
    return matcher.test(value.label) ||
           matcher.test(value.value) ||
           matcher.test(value.sku) ||
           matcher.test(value.application) ||
           matcher.test(value.discontinuedproductlist) ||
           matcher.test(value.type);
      
  }));
},

As mentioned, each of these values, has multiple strings of words within them.

Example of (value.application) data: "dry wet cold warm hot burned charred dirty clean soiled"

the sandman
  • 1,019
  • 3
  • 12
  • 32

1 Answers1

0

Was able to make this work by adding the "\b" regex property to each side of the search term (see matcherWords).

Now i can return letters combination matches for some of the categories, and only whole word matches for the others. Hopefully this helps someone else.

source: function(request, response) {

  var matcherLetters = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); // match letters in string
  var matcherWords = new RegExp("\\b" + $.ui.autocomplete.escapeRegex(request.term) + "\\b", "i"); // match words in string

  response($.grep(SearchList, function(value) {
  
    return matcherLetters.test(value.label) ||
           matcherLetters.test(value.value) ||
           matcherWords.test(value.sku) ||
           matcherWords.test(value.application) ||
           matcherWords.test(value.discontinuedproductlist) ||
           matcherWords.test(value.type);
  }));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
the sandman
  • 1,019
  • 3
  • 12
  • 32