【问题标题】:find and differentiate words in javascript [closed]在javascript中查找和区分单词[关闭]
【发布时间】:2021-06-29 14:48:08
【问题描述】:

我的 JavaScript 有问题。基本上我有一个文本:

const text = 'Hello Teddy Bear, enjoy your life'. 

我有一个包含两个元素的数组

const array = ['Teddy', 'Teddy Bear']; 

我只需要从这个数组中过滤“泰迪熊”。

我正在尝试使用 javascript 中的“包含”。但他找不到区别,因为文中也有“泰迪”..

有谁知道我该如何解决?谢谢

【问题讨论】:

  • 使用 .replace() 函数
  • 嗯..你能举个例子吗?
  • 如果是最长的匹配(子)字符串,其实很简单。 1st)sort 数组按其每个字符串项length 属性降序排列。 2nd)迭代数组......对于每个字符串项尝试它是否包含在给定文本中。停止使用第一个匹配的字符串项进行迭代。根本不需要正则表达式。

标签: javascript regex string ecmascript-6 filter


【解决方案1】:

如果它是可能的最长匹配(子)字符串,因此是最具体的,那么这个任务实际上可以很容易地解决。

  1. sort 数组按其每个字符串项的 length 属性降序排列。
  2. 迭代数组...对于每个字符串项,尝试它是否包含在给定文本中。
  3. 停止迭代第一个匹配的字符串项。

根本不需要正则表达式。

function getMostSpecificMatch(text, matchList) {
  let match;

  matchList
    .sort((a, b) => b.length - a.length)
    .some(str => {
      const doesMatch = text.includes(str);
      if (doesMatch) {

        match = str;
      }
      return doesMatch;
    });

  return match;
}

const sampleText = 'Hello Teddy Bear, enjoy your life';
const sampleList = ['Teddy', 'Teddy Bear'];

console.log(
  'randomly ordered list of possible matches ...',
  sampleList
);
console.log(
  "possible matches in descending order of each item's length ...",
  sampleList.sort((a, b) => b.length - a.length)
);
console.log({ sampleText });

console.log(
  'most specific match ...',
  getMostSpecificMatch(sampleText, sampleList)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

  • @ThadeuMunhózCesário ... 关于上述方法还有什么问题吗?
  • 不,彼得,非常感谢您的帮助!我将利用您的代码并针对我的情况进行一些调整。非常感谢!
猜你喜欢
  • 2014-07-26
  • 2016-04-21
  • 2020-04-26
  • 2021-10-09
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多