JQueryUI Autocomplete Search from Beginning

StuartProgramming Blog

I love the integrated Autocomplete in the JQueryUI but I have gotten requests to change the search behavior. The default behavior is to search for the target value anywhere in the string of the values supplied. This works natively by using something like the following code:

var matcher = new RegExp( term.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
 
return $.grep( array, function(value) { return matcher.test( value.label || value.value || value ); });

This takes the search term (“term”) from the textbox, escapes any characters that will mess up the regular expression, then performs a grep on the array testing each value (along with the value.value and value.label.)

This works very well for any instance where you want each value where the search term appears anywhere in the string, but what about restricting it to searching from the beginning only. In theory it's simple enough, you'll just need to add a caret (“^”) to the beginning of your regular expression. Here's how to do that without modifying the autocomplete code. You will simply replace your source option when declaring your autocomplete with one of the following.

  1. Local Array
    source: function( request, response ) {
       var matcher = new RegExp( "^" + request.term.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
       response($.grep(divisionSelectArray, function(value){return matcher.test(value.label || value.value || value); }) );
    }
    
  2. Remote values
    source: function(request, response) {
       $.ajax({
          url: "myurl.asp",
          dataType: "json",
          success: function( data ) {
             var matcher = new RegExp( "^" + request.term.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
             response($.grep(data, function(value){return matcher.test(value.label || value.value || value); }) );
          }
       });
    }