Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Make Twitter Typeahead Exact Match Words and Phrases

Twitters Typeahead matches any word anywhere in a phrase so for a search for "car" results can come from a phrase with a second word that matches "car". For instance when searching for car in a list with business card. Business card appears and even worse it appears before car. IE:

Search Term: Car
Suggestions:
Business Card
Car
Car Pool
Carbon

I want it to be more google and twitter like (they never suggest something that isn't matching exactly what is typed from the beginning) where the typed word is the most relevant, so Car would be more relevant when typing car than Business Card.

I want it to actually just STOP matching the second word until someone types a space and starts a second word. So in the above example business card would not appear in the list unless I typed:

Business C

How can I stop this behavior of matching and suggesting words that aren't an exact match from the start of the typed search.

Another way to say this would be how to stop the typeahead from tokenizing or splitting on the space. The typeahead always matches from the start of a word (^), so if the space wasn't recognized as a word boundary it would work more as google and twitters users would expect.

Thanks for any help, Tyler

UPDATE 1.

I updated my Dataset to return a Datum that has a value and token so that the typeahead _transformDatum method does not tokenize the tokens by splitting on a space. This works great and now it works as desired:

Values: Apple, Great Ape

Search Term: Ap Suggestions: Apple

This is what I want. But now there is a new issue.

ISSUE: When using a search term with a space no suggestions are returned.

So now when I type "great " the suggestions stop as soon as I type a space.:

Search Term: Great (with a space) Suggestions: (none)

I'm thinking that tokens can NOT have spaces. Even though the documentation doesn't explicitly say this in an issue:

The canonical form of a datum is an object with a value property and a tokens property. value is the string that represents the underlying value of the datum and tokens is a collection of strings that aid typeahead.js in matching datums with a given query.

like image 257
Tyler Carver Avatar asked Nov 13 '22 05:11

Tyler Carver


1 Answers

apt would be:

  matcher: function (item) {
      if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) == 0) {
          return true;
      }
  },
like image 121
Ankish Jain Avatar answered Nov 15 '22 11:11

Ankish Jain