fuzzy-match-filter.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fuzzy Search</title>
</head>
<body>
<input type="search" class="search">
<p class="response"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
// Fuzzy Search
function fuzzyMatch(needle, haystack){
// Declare Variables
var i = 0,
len = 0,
data = haystack.split(/\W/g),
pattern = '[' + needle.split('').join('+?') + '+?]',
regex = new RegExp(pattern, 'gi'),
matches = [],
matchString = '';
// Loop over data and create matches based on needle
for( i = 0, len = data.length; i < len; i++){
var thisMatch = data[i].match(regex);
if( thisMatch ){
matches.push({
name: data[i],
strength: thisMatch.length
});
}
}
// Sort the matches where the highest strength comes first
matches.sort(function(a,b){
return b.strength - a.strength;
});
// Output the matches
for (var key in matches) {
var obj = matches[key];
for (var prop in obj) {
if(obj.hasOwnProperty(prop)){
if( prop === 'name' ){
matchString += obj[prop] + '<br/>';
}
}
}
}
return matchString;
}
$(document).ready(function(){
var data = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.';
$('.search').on('keyup',function(){
$('.response').html( fuzzyMatch( this.value, data ) );
});
});
</script>
</body>
</html>