Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JS/jQuery to do string search/fuzzy matching?

entirely in JS, no server backend. I need to allow the user to search and then show a list of matched names. I'm using jQuery UI AutoComplete but need some JS to filter the results.

Given an Array of names:

Bob Hope
James Jones
Steve Jobs
Larry McBridge

Given a search term like Bo

How can I get just Bob Hope to return

Given a Search term like b:

How can I get all but James Jones?

Any simple JS for comparing two strings? Thanks

like image 895
AnApprentice Avatar asked Oct 30 '11 23:10

AnApprentice


People also ask

How do you do a fuzzy search?

A fuzzy search searches for text that matches a term closely instead of exactly. Fuzzy searches help you find relevant results even when the search terms are misspelled. To perform a fuzzy search, append a tilde (~) at the end of the search term.

What is fuzzy search Javascript?

Fuzzy searching matches the meaning, not necessarily the precise wording or specified phrases. It performs something the same as full-text search against data to see likely misspellings and approximate string matching.

Is fuzzy matching good?

Fuzzy string matching can help improve data quality and accuracy by data deduplication, identification of false-positives etc.


2 Answers

var names = ["Bob Hope","James Jones","Steve Jobs","Larry McBridge"]   
var query = "bo"
var results = $(names)
        .map(function(i,v){ 
            if(v.toLowerCase().indexOf(query.toLowerCase())!=-1){return v} 
        }).get()

// results is ["Bob Hope"]
like image 98
Ivan Castellanos Avatar answered Sep 24 '22 06:09

Ivan Castellanos


Maybe I misunderstood you (given the complexity of the above answer), but I came up with this which uses jQuery. Every time a key is pressed (when the input has focus), it searches all li elements on the page and finds whether they contain the search term.

Here is the HTML:

<ul><li>Bob Hope</li>
<li>James Jones</li>
<li>Steve Jobs</li>
<li>Larry McBridge</li></ul><br>
Search: <input id="search" length="24" />

And here is your jQuery:

$("#search").keyup(function(){
    $("li").hide();
   var term = $(this).val();
    $("li:contains('" + term + "')").show();
}); 
like image 3
Purag Avatar answered Sep 20 '22 06:09

Purag