首页 > 解决方案 > 在javascript中将列表中的单词与句子中的单词匹配的最佳方法是什么?

问题描述

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

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

它工作正常,但显然大写和标点符号会导致问题。我知道我需要在其中加入类似 .match() 的东西,但我不知道如何使用它。我相信这是有人在还没有找到代码之前所做的事情,任何参考也表示赞赏。

谢谢,

最好的

这哥们

标签: javascriptarraysstringstring-matching

解决方案


如果您正在寻找任何匹配的单词,您可以使用RegExpwith并使用created和flagString.prototype.replace验证匹配以允许不区分大小写。String.prototype.searchRegExpi

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


推荐阅读