【问题标题】:Derive keywords from search text从搜索文本中派生关键字
【发布时间】:2021-05-13 15:21:37
【问题描述】:

我正在尝试生成关键字来搜索和显示数据库中的一些内容。我提供了一个示例搜索文本和关键字,我想从关键字中派生出来。有人可以指导我如何实现从动态搜索字符串中获取关键字的逻辑,如下所示?

var searchText='My name is John santose mayer'

var Keywords={ 

  1: 'My name is John santose mayer',

  2: 'My name is johns santose',

  3: 'My name is John',

  4: 'My name is',

  5: 'My name'

  6: 'My'

}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    类似这样的使用reduce

    var searchText='My name is John santose mayer';
    
    
    let keywords = searchText.split(' ').reduce((prev, next) => {
      const concatWith =  prev[prev.length - 1] ?  prev[prev.length - 1] + ' ' : ''
      return [ ...prev, concatWith + next]
     
    }, []).reverse()
    
    console.log(keywords)

    【讨论】:

      【解决方案2】:
      const keywords = searchText.split(' ');
      const phrases = [];
      for(let length = keywords.length; length > 0; length--) {
        phrases.push(keywords.slice(0, length).join(' '));
      }
      

      【讨论】:

      • Split 不会给出我在查询中显示的搜索字符串
      【解决方案3】:

      splitmapslicereduce 的简单组合应该可以解决问题。

      const foo = "My name is John santose mayer"
          .split(" ")
          .map<string>((_, i, arr) => arr.slice(0, arr.length - i).join(" "))
          // [
          //     "My name is John santose mayer",
          //     "My name is John santose",
          //     "My name is John",
          //     "My name is",
          //     "My name",
          //     "My"
          //   ]
          .reduce<{ [key: number]: string }>((acc, curr, i) => {
              acc[i + 1] = curr;
              return acc;
          }, {});
      
      console.log(foo);
      // {
      //     "1": "My name is John santose mayer",
      //     "2": "My name is John santose",
      //     "3": "My name is John",
      //     "4": "My name is",
      //     "5": "My name",
      //     "6": "My"
      // }
      

      【讨论】:

        猜你喜欢
        • 2015-09-05
        • 2012-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 1970-01-01
        相关资源
        最近更新 更多