Help with custom fuzzy search


I’m trying to build a fuzzy search box, whereby when a user starts filling out the input field, it checks against the cities listed in the array and shows it below the input field in an unordered list containing the cities that match those characters. So for example if I typed “on” it would return Washington and Boston, or just the letter “s” would return Boston, Washington and Seattle. See JS Bin below. I got as far as seeing which characters from the input field are in the array, but am unsure how to return the city/cities with those characters in. Plus it seems to do a full string match, and not part.


The following script does what you want, although it is unlike your own example shown in this post. It works on the keyup event and checks the string in the input box with each of the strings in the cities array.

Here is the script, which is positioned just above the </body> tag in the example so that it starts after the page is loaded.

<script type="text/javascript">
// global vars
var cities = ['Chicago', 'Boston', 'Washington', 'Seattle', 'Detroit'];
var store=[];
var outputObj=document.getElementById("output"); 
var inputTextObj=document.getElementById("inputText");;

function process(obj)
 { var result, i=0;
   if(obj.value.length===0){ outputObj.value=""; return; }
     // ----
   store.length=0;    // initialise store
    { var citiesLC=cities[i].toLowerCase();
      var inTextLC=obj.value.toLowerCase();
       if(citiesLC.indexOf(inTextLC)!= -1){ store[store.length]=cities[i]; }
   if(store.length===0){ result="No matching cities";  }
   else { result=store.join(); } 

I have placed a working example in JSFiddle for you to play with.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.