Ad

Why Is Typeahead Matching Periods?

- 1 answer

I am using the same code from the typeahead example here. However if you type in a period . the dropdown will appear with matches. Is all this code above the array definition necessary? Is there an easier way to accomplish the same thing where you won't get matches for periods if there are no periods in your array?

I see the bloodhound example below it accomplishes the same thing and doesn't match periods but is it using var states to define an array and then using var states to construct a new bloodhound engine is this a mistake?

Copied code from the website:

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California',
  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
  'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
  'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
  'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
  'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
  'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
  'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
  'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
];

$('#the-basics .typeahead').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});

In my case I am generating an array of tags so instead of the states I am using var tags = <%= raw Tag.all.pluck(:name) %>;

Ad

Answer

You may find indexOf to be more useful than a regex for your application.

if (haystack.indexOf(needle) != -1) {
        /* needle is in haystack */
}

or, case insensitively:

if (haystack.toLowerCase().indexOf(needle.toLowerCase()) != -1) {
}

something like this:

function findMatches(q, cb) {
    var lq = q.toLowerCase();
    var matches = [];

    $.each(strs, function(i, str) {
        if (str.toLowerCase().indexOf(lq) != -1) matches.push(str);
    });

    cb(matches);
}
Ad
source: stackoverflow.com
Ad