Skip to content

Instantly share code, notes, and snippets.

@stanwmusic
Forked from davidgilbertson/typo-check.js
Created September 16, 2016 09:46
Show Gist options
  • Save stanwmusic/87f7a8701a8b758af0f46fd37d8a3545 to your computer and use it in GitHub Desktop.
Save stanwmusic/87f7a8701a8b758af0f46fd37d8a3545 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