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.

4
  • I'm not sure why you want to treat user input as regexp. Users will type random keywords, not (\b|^)foo[0-9]{2} :-? Commented Aug 8, 2011 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? Commented Aug 8, 2011 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. Commented Aug 8, 2011 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. Commented Aug 8, 2011 at 16:49

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@Stephen: I had misunderstood your question. Use Nick's answer; it will do exactly what you want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.