2

On the website I'm developing, I have a search box with which I would like to incorporate a live autosuggest feature. (If you know a better way than the route I'm going please let me know)

Here's what I have in mind: As the user types in the search bar, when the onchange event is triggered I want to send the query to the server (via ajax or websockets), then build a regex from the query (/^SOMELETTERS/gi), then search multiple fields (product names, brands, product numbers...) and match them to the regex. I want to gather the top 10 results and send them to the client side in json format to be used in an autosuggest script that's kind of like what google has.

These are my questions:
(1) Is there a better way?
(2) If no, how would I build a regex that matches items that begin with whatever the query is? ...I mean, what would the syntax be? I've tried a lot of things but they don't seem to work.

Stephen
  • 7,994
  • 9
  • 44
  • 73
  • I'm not sure why you want to treat user input as regexp. Users will type random keywords, not `(\b|^)foo[0-9]{2}` :-? – Álvaro González Aug 08 '11 at 15:48
  • I want to search terms that begin with the characters that the user has entered. It seems like building a regex would be the fastest way to search for that, wouldn't it be? – Stephen Aug 08 '11 at 15:57
  • 1
    Ah... Well, I don't think that doing a regexp search against `^foo` is faster than `LIKE 'foo%'` since the latter can make use of indexes. But I know nothing about MongoDB, perhaps it doesn't have LIKE. – Álvaro González Aug 08 '11 at 16:00
  • Alright, awesome, thanks! I don't know about MongoDB functionality too much, but as I was thinking about it I realized that it probably isn't going to be as robust as I'd want it to be. So I think I'm going to try Apache Solr to run the search. – Stephen Aug 08 '11 at 16:49

1 Answers1

3

Call the constructor of the RegExp object. MSDN Docs.

If you have req.params.q you can:

var rx = new Regex(req.params.q);
Nick Radford
  • 1,038
  • 6
  • 13