使用 Lodash 获取字符串数组的部分字符串匹配

问题描述 投票:0回答:1

我有一个字符串数组,想要使用 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);
javascript arrays lodash
1个回答
0
投票

实现模糊匹配的一种方法是使用

_.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>

© www.soinside.com 2019 - 2024. All rights reserved.