Generate a similarity score between two strings in JavaScript
This post will discuss how to generate a similarity score between two strings in JavaScript.
String similarity is a measure of how closely two strings match each other, based on some criteria or algorithm. Here are some of the most common functions, along with some examples and explanations:
1. Using Dice’s Coefficient
Dice’s Coefficient is a statistic that measures the overlap between two sets of elements, such as characters in a string. The score ranges from 0 to 1, where 0 means no similarity and 1 means exact match. We can use the string-similarity library that has a function compareTwoStrings() returning a similarity score between two strings, based on Dice’s Coefficient. We can install this library using npm or yarn. For example, the following code compares few strings and log their similarity coefficient score.
|
1 2 3 4 5 |
let _ = require("string-similarity"); console.log(_.compareTwoStrings("Hello world", "Hello world")); // 1 console.log(_.compareTwoStrings("Hello world", "Hello World")); // 0.7777777777777778 console.log(_.compareTwoStrings("Hello world", "Hello there")); // 0.4444444444444444 |
Alternatively, we can use the string-similarity-js library that also uses Dice’s Coefficient to measure the similarity between two strings based on the number of bigrams (pairs of adjacent letters) they have in common. The library returns a score between 0 and 1, where a higher number means more similarity. We can install this library using npm or import it as a module.
|
1 2 3 4 5 |
let _ = require("string-similarity-js"); console.log(_.stringSimilarity("Hello world", "Hello world")); // 1 console.log(_.stringSimilarity("Hello world", "Hello World")); // 1 console.log(_.stringSimilarity("Hello world", "Hello there")); // 0.5 |
2. Using Levenshtein distance algorithm
Another option is to use the Levenshtein distance algorithm, which is a measure of how many edits (insertions, deletions, or substitutions) are needed to transform one string into another. We can use an existing library such as js-levenshtein that returns the Levenshtein distance between two strings. The lower the distance, the higher the similarity.
|
1 2 3 4 5 |
const levenshtein = require('js-levenshtein'); console.log(levenshtein("Hello world", "Hello world")); // 0 console.log(levenshtein("Hello world", "Hello World")); // 1 console.log(levenshtein("Hello world", "Hello there")); // 5 |
We can also implement this algorithm ourself by using a nested loop or a recursive function. For example, the following code calculates the Levenshtein distance between two strings using a nested loop. The return value of this function can be modified to suit our specific needs and preferences.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
function levenshteinSimilarity(str1, str2) { // Get the lengths of the two strings let m = str1.length; let n = str2.length; // Initialize an empty array of size (m + 1) x (n + 1) let matrix = []; // Fill the first row and column with values from 0 to m and 0 to n for (let i = 0; i <= m; i++) { matrix[i] = [i]; } for (let j = 0; j <= n; j++) { matrix[0][j] = j; } // Loop through the remaining cells of the matrix for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { // Calculate the cost of substitution let cost = str1[i - 1] === str2[j - 1] ? 0 : 1; // Find the minimum of three values: insertion, deletion, and substitution matrix[i][j] = Math.min( matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost ); } } // Return the normalized Levenshtein distance score in % return (1 - matrix[m][n] / Math.max(m, n)) * 100; } console.log(levenshteinSimilarity("Hello world", "Hello world")); // 100 console.log(levenshteinSimilarity("Hello world", "Hello World")); // 90.9090909090909 console.log(levenshteinSimilarity("Hello world", "Hello there")); // 54.54545454545454 |
3. Using a custom function
Finally, we can also write our own function that calculates the similarity percentage between two strings based on their length and character matching. For example, the following code creates a function that compares two strings and returns their similarity percentage. We can also modify this function to suit our specific needs and preferences.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function similarityScore(s1, s2) { let longer = s1; let shorter = s2; if (s1.length < s2.length) { longer = s2; shorter = s1; } let longerLength = longer.length; if (longerLength === 0) { return 1.0; } let matchCount = 0; for (let i = 0; i < longerLength; i++) { if (longer[i] === shorter[i]) { matchCount++; } } return (matchCount / longerLength) * 100; } console.log(similarityScore("Hello world", "Hello world")); // 100 console.log(similarityScore("Hello world", "Hello World")); // 90.9090909090909 console.log(similarityScore("Hello world", "Hello there")); // 54.54545454545454 |
That’s all about generating a similarity score between two strings in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)