In this post we will see how can we search similar strings within the array of strings compared to input string.
We will using a npm package known as string-similarity.
String-similarity finds degree of similarity between two strings, based onĀ Dice’s Coefficient
Using this package we will find the best matches from the array of multiple strings.
Install the npm package through node console as shown below:
>npm install string-similarity –save
Let us see how it works,
var stringSimilarity = require('string-similarity'); var inputString = "Log in"; var arrayofStrings = ["Sign in", "Log out", "Likes", "User Login", "thewebspark", "Admin Login"]; var matches = stringSimilarity.findBestMatch(inputString, arrayofStrings); console.log(matches); //produces response with rating to each string //initialize an empty array to store similar strings var getSimilar = []; for(var i in matches.ratings){ if(matches.ratings[i].rating > 0.2){ getSimilar.push(matches.ratings[i].target); } } console.log("The similar strings for "+inputString+"are: \n" +getSimilar);
Below would be the output for the above code:
Higher the rating score, better the match. Works nicely with lengthy strings also.
The things is we just have sort it out based on the score/ratings assigned to strings from the array. The rest is done by this API calledĀ string-similarity