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.
JavaScript
x
4
1
// Example
2
string1 = "The lazy fox jumps over the fence" // (7 words)
3
string2 = "The lazy dog jumps under a fence yesterday" // (8 words)
4
Output: 4
Accuracy is (4 correct words/7 words to check) = 57%
Any idea will be appreciated
Advertisement
Answer
You could split
each string to words and match the same words by using filter
JavaScript
1
19
19
1
function getWords(str) {
2
return str.split(" ").filter(Boolean);
3
}
4
5
function getMatchedWords(words1, words2) {
6
return words1.filter((word) => words2.includes(word));
7
}
8
9
const string1 = "The lazy fox jumps over the fence";
10
const string2 = "The lazy dog jumps under a fence yesterday";
11
12
const words1 = getWords(string1);
13
const words2 = getWords(string2);
14
15
const matchedWords = getMatchedWords(words1, words2);
16
17
const ratio = +((100 * matchedWords.length) / words1.length).toPrecision(2);
18
19
console.log(ratio);