我有一个字符串数组,想要使用 Lodash 查找部分字符串匹配。我希望搜索能够找到完整匹配项(例如与
broken
),但也希望找到部分匹配项(例如 virus
是 viruses
的一部分)
const textToSearch = 'The broken ship that caught fire also had viruses onboard';
const arrayOfKeywords = ['virus', 'fire', 'broken'];
到目前为止,我有一个方法可以将 textToSearch 拆分为一个数组,然后使用
_.include()
查找完整匹配项
const tokenize = text =>
text
.split(/(\w+)/)
.map(x =>
_.includes(arrayOfKeywords, x.toLowerCase())
? {content: x, type: 'keyword'}
: x
);
const tokens = tokenize(textToSearch);
_.some
函数和自定义谓词来检查部分匹配。比如:
const textToSearch = 'The broken ship that caught fire also had viruses onboard';
const arrayOfKeywords = ['virus', 'fire', 'broken'];
const tokenize = text =>
text
.split(/(\w+)/)
.map((x) =>
_.some(arrayOfKeywords, (keyword) => x.toLowerCase().includes(keyword.toLowerCase()))
? { content: x, type: 'keyword' }
: x
);
const tokens = tokenize(textToSearch);
console.log(tokens);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>