Check similarity between strings in Javascript

Viewed 1100

How to compare 2 text strings to see if they are similar, for example:

var a = "Hello Blue World";
var b = "Hello Blut World?";

if(a similar b)
{
    console.log(true);
}
3 Answers

You could use string-similarity library.

Finds degree of similarity between strings, based on Dice's Coefficient, which is mostly better than Levenshtein distance.

var a = "Hello Blue World";
var b = "Hello Blut World?";

var stringSimilarity = require("string-similarity");
var similarityCoef = stringSimilarity.compareTwoStrings(a, b);

if (similarityCoef > 0.8) { console.log(true); }

Note that similarityCoef print true when the string matches at 80% (0.8). You can adjust this value to your needs.

That's tricky. Because you have somehow to tell in percent what similarity means for you. What about this approach?

You compare them string by string and count the matches. I know that this will fail as soon as there is one additional character very early in one of the strings. But for a start it should suffice.

var a = "Hello Blue World";
var b = "Hello Blut World?";

 // only compare both strings with their mutual length, because of the loop we use
const mutualLength = (a.length > b.length) ? b.length : a.length;
const similarityAt = 90; // percent
let matchCount = 0;

// with each match increase matchCount by 1
for (let pointer = 0; pointer < mutualLength; pointer++) {
    if (a.substring(pointer, 1) === (b.substring(pointer, 1) {
        matchCount++;
    }
}

 // compute similarity in percent
const similarity = (matchCount * 100) / mutualLength;

console.log('Similarity given: ' + (similarity >= similarityAt));

B"H

Depends on degree of similarity, but if you want a percent amount to tell you what matches, you can simply loop through the shortest, and keep track of how many times each character matches with the subsequent index of the longest string (or add whitespace to the shortest string, but that might mess up some calculations), and then divide the total number of matches with the length of the (shortest) string to get the percent of equality


var str1 = "Hello blue world"
var str2 = "Hello blut world?!"

var shortest = str2.length >= str1.length?str1:str2
var longest = str2.length < str1.length?str1:str2

var matches= 0

shortest
.split("")
//Just check if index of shortest
//Matches index of longest, and if so (&& means do next
//Expression) add the total number of matches by one
.forEach (
(x,k)=>
((x==longest[k]) && (matches++) )
)

//Final result, divide matches by total length
var similarity = matches / shortest.length
Related