0

Let's say I have three strings:

var s1 = 'Tokyo';
var s2 = 'Tokyo is pretty neat';
var s3 = 'Tokyo is pretty neat at summer';

And I wanna compare s3 to s2 and s1 and find the 'best' match for s3 among s1 and s2. I mean, the matching algorithm should return s2 in this case, as it has more in common with s3. How can I do that? As a rule, simple check using indexOf() was enough for me, but now I need to find the 'best' match.

yxfxmx
  • 665
  • 1
  • 6
  • 13

2 Answers2

0

Take a look at Levenshtein distance algorithm.

Basically, it takes two strings and finds the difference between them. If the distance between the two strings are small it means that the strings are more similar to each other.

Let's take your example

Query: Tokyo is pretty neat at summer

S2: Tokyo is pretty neat = 10

S3: Tokyo = 25

Online Demo of the algorithm

Here is a javascript library

Stian Standahl
  • 2,506
  • 4
  • 33
  • 43
0

Based on your question and comments, this example should suffice.

var tests = [
    'Tokyo',
    'Tokyo is pretty neat'
    ],
    actual = 'Tokyo is pretty neat at summer';

var firstClosest = tests.reduce(function (acc, test) {
    if (test === actual.slice(0, test.length) && test.length > acc.length) {
        acc = test;
    }
    
    return acc;
}, '');

document.getElementById('out').textContent = firstClosest;
<pre id='out'></pre>
Xotic750
  • 22,914
  • 8
  • 57
  • 79