Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/65869053/count-the-number-of-matching-words-between-two-strings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...