0

I am working on a search engine for bands and I want to make it so that the user doesn't need to type the article to find the band. So, for example, if someone wanted to find "The Black Keys," they could find them by typing "Bla," "Black Keys," "The Black Keys," or any variation like that. Here is what I have so far:

matcher = new RegExp( '^(?<=the)'+searchstring, 'i' );
Colin
  • 2,428
  • 3
  • 33
  • 48
  • Have you considered using database's search engine? – Rafał Walczak Apr 13 '14 at 18:25
  • possible duplicate of [Matching an optional substring in a regex](http://stackoverflow.com/questions/241285/matching-an-optional-substring-in-a-regex) – Anonymous Apr 13 '14 at 18:26
  • JavaScript doesn't support lookbehind. Try matcher = new Regexp( '^(?:the|The)(.*?)' instead – Hektor Apr 13 '14 at 18:27
  • Are you sending the partial string to your server or filtering data that is already sent to the client or using an autocomplete plugin in your search field? – Jason Aller Apr 13 '14 at 18:28
  • @JasonAller I'm using an autocomplete plugin (jQuery-UI's) with data that has already been sent to the client – Colin Apr 13 '14 at 18:28
  • To clarify you are doing something similar to this: [jQuery UI Autocomplete Partial Match](http://stackoverflow.com/questions/15179180/jquery-ui-autocomplete-partial-match), but you want to be able to optionally skip articles? – Jason Aller Apr 13 '14 at 18:32
  • I'm not sure I see the similarity, but I do want to optionally skip articles that are at the beginning of a string – Colin Apr 13 '14 at 18:34

1 Answers1

2

This is a start:

var tags = ["c++", "java", "the php", "coldfusion", "a javascript", "asp", "the ruby"];
$("#autocomplete").autocomplete({
    source: function (request, response) {
        var matcher = new RegExp("^(?:(the|a) )?" + $.ui.autocomplete.escapeRegex(request.term), "i");
        response($.grep(tags, function (item) {
            return matcher.test(item);
        }));
    }
});

The regex is modified to:

  • ^ - start of word
  • (?: - begin a non capturing group
  • (the|a) - your list of articles
  • - the space between words
  • )? close non capture group and make it optional.

a working fiddle

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • That's perfect! Thank you so much! One thing I never understood: Why should I use an actual space instead of "\s"? – Colin Apr 13 '14 at 19:21
  • `\s` would probably be a good improvement. I was even playing with the right way to use `\b\` for word boundary. – Jason Aller Apr 13 '14 at 19:25