Skip to content

Instantly share code, notes, and snippets.

@hhkaos
Created April 7, 2021 05:06
Show Gist options
  • Save hhkaos/7ef8d5046868a8cf1d792e08e14d9e37 to your computer and use it in GitHub Desktop.
Save hhkaos/7ef8d5046868a8cf1d792e08e14d9e37 to your computer and use it in GitHub Desktop.
Check if two strings are similar using string-similary
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta
http-equiv="X-UA-Compatible"
content="IE=edge"
>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
>
<title>JavaScript check if strings are similar</title>
</head>
<body>
<h1>Check if two strings are similar using string-similarity</h1>
<script src="//unpkg.com/string-similarity/umd/string-similarity.min.js"></script>
<label>Reponse: </label>
<input
type="text"
id="inputTxt"
>
<span id="status"></span>
<p>Please open the Developer Console console</p>
<style>
#status {
color: red;
}
#status.correct {
color: green;
}
</style>
<script>
// https://www.npmjs.com/package/string-similarity
const responses = [
"Magallanes",
"Elcano",
"La vuelta al mundo",
"Circunvalación",
"Circunavegación",
"Expedición"
];
const inputTxt = document.getElementById("inputTxt"),
statusEl = document.getElementById("status");
const Similarity = function (value, term, distance) {
this.value = value;
this.term = term;
this.distance = distance;
};
inputTxt.addEventListener("keyup", () => {
let table = [];
let isSimilar = false;
responses.forEach(validStr => {
const inputValue = inputTxt.value.toLocaleLowerCase();
validStr = validStr.toLocaleLowerCase()
const distance = stringSimilarity.compareTwoStrings(validStr, inputValue);
if (distance >= .8) {
isSimilar = true;
}
table.push(new Similarity(inputValue, validStr, distance))
});
if (isSimilar) {
statusEl.innerText = "Correct!";
if (!statusEl.classList.contains("correct")) {
statusEl.classList.toggle("correct");
}
} else {
if (statusEl.classList.contains("correct")) {
statusEl.classList.toggle("correct");
}
statusEl.innerText = "Incorrect!";
}
console.table(table);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment