Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active October 19, 2017 20:44
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidgilbertson/00e3f049e87c4d1fff10dd81e114d5f6 to your computer and use it in GitHub Desktop.
Save davidgilbertson/00e3f049e87c4d1fff10dd81e114d5f6 to your computer and use it in GitHub Desktop.
function checkForCloseMatch(longString, shortString) {
// too many false positives with very short strings
if (shortString.length < 3) return '';
// test if the shortString is in the string (so everything is fine)
if (longString.includes(shortString)) return '';
// split the shortString string into two at each postion e.g. g|mail gm|ail gma|il gmai|l
for (let i = 1; i < shortString.length; i++) {
const firstPart = shortString.substring(0, i);
const secondPart = shortString.substring(i);
// test for wrong letter
const wrongLetterRegEx = new RegExp(`${firstPart}.${secondPart.substring(1)}`);
if (wrongLetterRegEx.test(longString)) {
return longString.replace(wrongLetterRegEx, shortString);
}
// test for extra letter
const extraLetterRegEx = new RegExp(`${firstPart}.${secondPart}`);
if (extraLetterRegEx.test(longString)) {
return longString.replace(extraLetterRegEx, shortString);
}
// test for missing letter
if (secondPart !== 'mail') {
const missingLetterRegEx = new RegExp(`${firstPart}{0}${secondPart}`);
if (missingLetterRegEx.test(longString)) {
return longString.replace(missingLetterRegEx, shortString);
}
}
// test for switched letters
const switchedLetters = [
shortString.substring(0, i - 1),
shortString.charAt(i),
shortString.charAt(i - 1),
shortString.substring(i + 1),
].join('');
if (longString.includes(switchedLetters)) {
return longString.replace(switchedLetters, shortString);
}
}
// if nothing was close, then there wasn't a typo
return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment