这是一个肮脏的实现,可以让你使用Levenshtein distance
. “levenshteinenator”的功劳归于this link
. 您可以将所需的任何流行域添加到域数组中,它会检查输入的电子邮件的主机部分的距离是 1 还是 2,这将合理地接近假设某处有错字。
levenshteinenator = function(a, b) {
var cost;
// get values
var m = a.length;
var n = b.length;
// make sure a.length >= b.length to use O(min(n,m)) space, whatever that is
if (m < n) {
var c=a;a=b;b=c;
var o=m;m=n;n=o;
}
var r = new Array();
r[0] = new Array();
for (var c = 0; c < n+1; c++) {
r[0][c] = c;
}
for (var i = 1; i < m+1; i++) {
r[i] = new Array();
r[i][0] = i;
for (var j = 1; j < n+1; j++) {
cost = (a.charAt(i-1) == b.charAt(j-1))? 0: 1;
r[i][j] = minimator(r[i-1][j]+1,r[i][j-1]+1,r[i-1][j-1]+cost);
}
}
return r[m][n];
}
// return the smallest of the three values passed in
minimator = function(x,y,z) {
if (x < y && x < z) return x;
if (y < x && y < z) return y;
return z;
}
var domains = new Array('yahoo.com','google.com','hotmail.com');
var email = 'whatever@yahoo.om';
var parts = email.split('@');
var dist;
for(var x=0; x < domains.length; x++) {
dist = levenshteinenator(domains[x], parts[1]);
if(dist == 1 || dist == 2) {
alert('did you mean ' + domains[x] + '?');
}
}