Skip to content

Instantly share code, notes, and snippets.

@IgorInger
Created January 4, 2012 21:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save IgorInger/1562394 to your computer and use it in GitHub Desktop.
Save IgorInger/1562394 to your computer and use it in GitHub Desktop.
Levenshtein distance (jQuery plugin)
(function($) {
$.fn.levenshteinDistance = function(u, v) {
var m = u.length;
var n = v.length;
var D = [];
for(var i = 0; i <= m; i++) {
D.push([]);
for(var j = 0; j <= n; j++) {
D[i][j] = 0;
}
}
for(var i = 1; i <= m; i++) {
for(var j = 1; j <= n; j++) {
if (j == 0) {
D[i][j] = i;
} else if (i == 0) {
D[i][j] = j;
} else {
D[i][j] = [D[i-1][j-1] + (u[i-1] != v[j-1]), D[i][j-1] + 1, D[i-1][j] + 1].sort()[0];
}
}
}
return D[m][n];
};
})(jQuery);
@mrswadge
Copy link

This works great in Chrome, but always returns 0 in IE8 as u[i-1] and v[j-1] evaluates to undefined. Instead use str.charAt( index ) and it will work.

i.e.
D[i][j] = [D[i-1][j-1] + (u.charAt(i-1) != v.charAt(j-1)), D[i][j-1] + 1, D[i-1][j] + 1].sort()[0];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment