How To: Modify jquery.autocomplete regex to show results that starts with the given input
Asked Answered
M

1

5

I dont know enough to modify following code that will show me the word starting with the inputted characters.For eg.: If I type E or e it shows me "Electrical,Electronics,Mechanical" but I want only "Electrical,Electronics" to be displayed.How to do this?

I am using jquery autocomplete plugin.

source: function(request, response) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
        response(select.children("option").map(function() {

         var text = $(this).text();
         if (this.value && (!request.term || matcher.test(text)))
             return {
             label: text.replace(
                 new RegExp(
                 "(?![^&;]+;)(?!<[^<>]*)(" +
                     $.ui.autocomplete.escapeRegex(request.term) +
                     ")(?![^<>]*>)(?![^&;]+;)", "gi"
                 ), "<strong>$1</strong>"),
             value: text,
             option: this
            };
      }));
Mckinnie answered 15/12, 2011 at 12:44 Comment(0)
A
10

In Javascript RegExp, ^ means startsWith:

var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
Adara answered 15/12, 2011 at 13:12 Comment(2)
@Mckinnie The 'i' parameter means that the regular expression will ignore case. In other words, the search will not be case sensitive, so, if you type 'm' lowercase, it still will return 'Mechanical' as a result.Adara
Thanks a lot falsarella,it is working exactly as I wanted...thank you very much...Mckinnie

© 2022 - 2024 — McMap. All rights reserved.