Skip to content

Count the number of matching words between two strings

Hello I would like to ask some help how I can do this in Jquery

Count the number of matching words (in order) between two strings so I can generate accuracy.

// Example
string1 = "The lazy fox jumps over the fence" // (7 words)
string2 = "The lazy dog jumps under a fence yesterday" // (8 words)

Output: 4

Accuracy is (4 correct words/7 words to check) = 57%

Any idea will be appreciated

Answer

You could split each string to words and match the same words by using filter

function getWords(str) {
  return str.split(" ").filter(Boolean);
}

function getMatchedWords(words1, words2) {
  return words1.filter((word) => words2.includes(word));
}

const string1 = "The lazy fox jumps over the fence";
const string2 = "The lazy dog jumps under a fence yesterday";

const words1 = getWords(string1);
const words2 = getWords(string2);

const matchedWords = getMatchedWords(words1, words2);

const ratio = +((100 * matchedWords.length) / words1.length).toPrecision(2);

console.log(ratio);