我有两个句子,我想找到它们共享的所有单词,无论大小写或标点符号如何。 目前,这就是我正在做的事情:
searchWords = sentence1.split(" ");
var wordList = sentence2.split(" ");
const matchList = wordList.filter(value => -1 !== searchWords.indexOf(value));
它工作正常,但显然大写和标点符号会导致问题。 我知道我需要在其中加入类似 .match() 的内容,但我不知道如何使用它。我确信这是有人之前做过的事情,只是还没有找到代码,任何引用资料也将受到赞赏。
谢谢,
最佳
这家伙。
最佳答案
如果您正在寻找任何匹配的单词,您可以使用 RegExp
与 String.prototype.replace
并使用 String.prototype.search
验证匹配与创建的RegExp
和一个i
标记允许不区分大小写。
function compare(str1, str2, matches = []) {
str1.replace(/(\w+)/g, m => str2.search(new RegExp(m, "i")) >= 0 && matches.push(m));
return matches;
}
console.log( compare("Hello there this is a test", "Hello Test this is a world") );
如果您正在寻找匹配的特定单词,您可以使用functional composition
至split
每个字符串都变成 Array
,按可能的 matches
过滤每个,然后根据其中一个进行筛选。
function compare(str1, str2, matchables) {
let containFilter = (a) => (i) => a.includes(i),
matchFilter = s => s.toLowerCase().split(" ").filter(containFilter(matchables));
return matchFilter(str1).filter(containFilter( matchFilter(str2) ));
}
let matchables = ["hello", "test", "world"];
console.log( compare("Hello there this is a test", "Hi Test this is a world", matchables) );
关于javascript - 在javascript中将列表中的单词与句子中的单词相匹配的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57733028/