I thought of this idea and implemented it on my own site, basically whenever the user encounters a 404 page, instead of just giving a 404 message it provides or even redirects to the likely correct url. First it compares the distance between window.location.pathname and each of the correct paths on the website and returns the closest one. This uses the edit distance between them, using this snippet:
function distance(s1, s2) {
s1 = s1.toLowerCase(); // Case doesn't matter in url's
s2 = s2.toLowerCase();
var costs = new Array();
for (var i = 0; i <= s1.length; i++) {
var lastValue = i;
for (var j = 0; j <= s2.length; j++) {
if (i == 0) costs[j] = j;
else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0) costs[s2.length] = lastValue;
}
return costs[s2.length];
}
Then, to get the closest url I do this:
function closest(str) {
var urls = ['index', 'blog', 'projects']; //Correct url's
urls.sort((a, b) => editDistance(a, str) - editDistance(str, b));
return urls[0];
}
Now I can check how close these are, if they're 1 or 2 letters different than it's likely that the user meant that url:
I thought of this idea and implemented it on my own site, basically whenever the user encounters a 404 page, instead of just giving a 404 message it provides or even redirects to the likely correct url. First it compares the distance between
window.location.pathname
and each of the correct paths on the website and returns the closest one. This uses the edit distance between them, using this snippet:Then, to get the closest url I do this:
Now I can check how close these are, if they're 1 or 2 letters different than it's likely that the user meant that url:
Either way this makes an amazing user experience on any website and we should definitely do this on Scratch Addons.
(Also you can try it here or for no redirect here )