javascript - 在javascript中将列表中的单词与句子中的单词相匹配的最佳方法是什么?

标签 javascript arrays string string-matching

我有两个句子,我想找到它们共享的所有单词,无论大小写或标点符号如何。 目前,这就是我正在做的事情:

    searchWords = sentence1.split(" ");
    var wordList = sentence2.split(" ");
    const matchList = wordList.filter(value => -1 !== searchWords.indexOf(value));

它工作正常,但显然大写和标点符号会导致问题。 我知道我需要在其中加入类似 .match() 的内容,但我不知道如何使用它。我确信这是有人之前做过的事情,只是还没有找到代码,任何引用资料也将受到赞赏。

谢谢,

最佳

这家伙。

最佳答案

如果您正在寻找任何匹配的单词,您可以使用 RegExpString.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 compositionsplit每个字符串都变成 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/

相关文章:

php - 是否有一个 PHP 函数可以计算一个值在数组中出现的次数?

javascript - 如何将javascript对象拆分成更小的部分

JAVA - 将 "Stringed"数组解析为实际数组

javascript - 从本地存储阵列中删除 1 项

javascript - 为什么~0是-1?

javascript - 关于 iPad 中 CSS 悬停/鼠标悬停的问题

javascript - 如何用 javascript 中获取的数据中的另一个数组替换整个数组

C++ 数组 Visual Studio 2010 与 Bloodshed Dev-C++ 4.9.9.2

python - 交换 2+ 字串中的字母

javascript - VueJS 如何将计算属性与 v-for 一起使用