首页 > 解决方案 > 检查数据库中“单词”集合中的所有单词,并检查文本中的任何单词是否与任何单词匹配

问题描述

我在数据库 MongoDB 中有一个名为 words 的集合,它存储所有单词。它们已通过后端查询提取并推送到前端。

这是在前端完成的:

this.annotationSub = this.annotationService
      .getWordUpdateListener()
      .subscribe((thewords: ComplexWord[]) => {
        this.thewords = thewords;
        this.thewords.map(word => {
          if (word.word === this.setWord) {
            this.wordIWant = word.word;
        }
         console.log(word);
      });

console.log(word);上面给出这些字段=

{word: "Lorem", annotation: "Explain Lorem"},
{word: "Aenean", annotation: "Explain Aenean"},
{word: "Hello", annotation: "Explaining Hello"}

这将检索所有文本:

this.postsService.getPosts();
    this.postsSub = this.postsService
      .getPostUpdateListener()
      .subscribe((posts: Post[]) => {
        this.posts = posts;
        this.posts.map(post => {
          if (post.id === this.id) {
            this.postIWant = post.fileText;
          }
        });
      });

this.postIWant已经从帖子中得到了所有的文字。

现在如何检查是否有任何单词与中的文本匹配this.postIWant

提前谢谢了

标签: javascriptmongodb

解决方案


这是最好的解决方案。

将文本传递给函数:

function complexWordIdentification(text) {
  const complexWords = ['Hello', 'World', 'Complex Phrase'];
  const results = [];
  let match, regexp, result;

  for (let i = 0; i < complexWords.length; i++) {
    // the complex word we are checking in this iteration
    const complexWord = complexWords[i];
    regexp = new RegExp(complexWord, 'g');

    while ((match = regexp.exec(text)) !== null) {

      result = {
        begin: (regexp.lastIndex - complexWords[i].length),
        end: regexp.lastIndex,
        text: complexWord
      };
      results.push(result);
    }
  }
  return results;
}

推荐阅读