Search code examples
javascriptsearch-engine

Simple search engine with javascript. Any suggestion?


I would to make a simple search engine with javascript. The idea is to read a server-side text file, parse it and find any expression that matches user's query. And yes, I must use client-side scripting.

Do you have any suggestion ?

Thanks .

EDIT - Details to answer comments

I need to parse 1 single file (max. 10.000 lines). I do not need an auto-complete: I just want to display strings matching query in a SELECT element. Also, I would like to avoid using JQuery if possible.


Solution

  • You will have cross browser problems with the request so using a library that abstracts this IS a smart choice. However here is a possible skeleton for the needed calls.

    Be assured that storing a large file in a javascript variable is not very cleaver. Beware on what you are doing!

    var words = [];
    var query = "";
    
    function parseText(data) {
     // taking care of data
     // check null handle errors
     var data = data.replace(/\W+/g,' '); // replace non words with spaces
     words = data.split(' '); // split and cache this if you need it again without refetching
     doSearch(query);
    }
    
    function doSearch(query) {
      // handle the loop trough the array
      // you may save the data into a variable and use regex instead of splitting into an array
    }
    
    function handler() {
     if(this.readyState == 4 && this.status == 200) {
      // so far so good
      if(this.responseXML != null && this.responseXML != "")
         // success!
       parseText(this.responseXML);
      else
       parseText(null);
     } else if (this.readyState == 4 && this.status != 200) {
      // fetched the wrong page or network error...
      parseText(null);
     }
    }
    
    query = "someword";
    var client = new XMLHttpRequest();
    client.onreadystatechange = handler;
    client.open("GET", "/remote.txt");
    client.send();