Javascript: calculating similarity % between two string

PHOTO EMBED

Sun Aug 28 2022 22:53:52 GMT+0000 (UTC)

Saved by @marcopinero #html #javascript #css

body{
    font-family: verdana;
    color:gray;
    margin: 8px;
}

.str{
    color:#F0F;
}

.perc{
    color:#000;
    background-color:#FF0;
}

.comment{
    color:silver;
}

p{
    color: black;
    font-style:italic;
}

<html>
    <head>
        <title>
            test
        </title>
    </head>
    <body>
This is a way to calculate similarity % between two strings based on <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance:</a><p><p><br>
    </body>
</html>

function similarity(s1, s2) {
  var longer = s1;
  var shorter = s2;
  if (s1.length < s2.length) {
    longer = s2;
    shorter = s1;
  }
  var longerLength = longer.length;
  if (longerLength === 0) {
    return 1.0;
  }
  return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}

function editDistance(s1, s2) {
  s1 = s1.toLowerCase();
  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];
}

var $str1="Marco Antonio Piñero Lopez";
var $str2="marco antonio Pineda lópez";

var perc=Math.round(similarity($str1,$str2)*10000)/100;

var txt="The strings: <span class=\"str\">'"+$str1+"'</span> and <span class=\"str\">'"+$str2+"'</span>";
  txt+="<br>are similar <span class=\"perc\">"+perc+"%</span>";
document.write(txt);

content_copyCOPY