javascript - 在javascript中将列表中的单词与句子中的单词匹配的最佳方法是什么?
问题描述
我有两个句子,我想找到它们共享的所有单词,无论大小写或标点符号如何。目前这就是我正在做的事情:
searchWords = sentence1.split(" ");
var wordList = sentence2.split(" ");
const matchList = wordList.filter(value => -1 !== searchWords.indexOf(value));
它工作正常,但显然大写和标点符号会导致问题。我知道我需要在其中加入类似 .match() 的东西,但我不知道如何使用它。我相信这是有人在还没有找到代码之前所做的事情,任何参考也表示赞赏。
谢谢,
最好的
这哥们
解决方案
如果您正在寻找任何匹配的单词,您可以使用RegExp
with并使用created和flagString.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) );
推荐阅读
- python - pyinstaller如何在文件夹中包含.py
- delphi - Delphi FMX TListview - DynamicAppearance 模式 - 访问冲突问题
- c# - 在连接字符串中包含服务名称的语法是什么?
- image - 从 RGB 值重绘后,图像现在具有黄色色调
- c - 是否可以将函数的返回值作为 C 中主函数的返回值传递?
- mysql - 重命名 Django 模型时的最佳实践是什么?[数据库:MySQL、PostgreSQL 或 SQLite]
- excel - 是否可以使用 OpenXML SDK 创建加密的 Excel 文件
- fb-hydra - 确认递归实例化将允许分层对象实例化
- java - 使用 CommonsCli,我如何解析一个可以多次出现并且具有灵活数量的值的选项?
- dataframe - 使用 DataFramesMeta 包中的 @linq 在 Julia 中整理数据