Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if two strings are similar in Javascript?

Let's say I have two strings, is there any way to check if they are at least 90% similar?

var string1 = "theBoardmeetstoday,tomorrow51";
var string2 = "Board meets today, tomorrow";

Thanks,

Tegan

like image 463
Tegan Snyder Avatar asked Oct 14 '10 16:10

Tegan Snyder


People also ask

How can I compare two strings in JavaScript?

To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.

How do you determine if two strings are similar?

You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Can I use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

What is === in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.


2 Answers

The wikipedia entry for Levenshtein distance includes a sample implementation.

like image 55
rtalbot Avatar answered Oct 03 '22 05:10

rtalbot


jsdifflib is a JavaScript port of Python's excellent difflib library.

It has a function ratio() which "return[s] a measure of the sequences’ similarity as a float in the range [0, 1]."

like image 29
RichieHindle Avatar answered Oct 03 '22 07:10

RichieHindle