首页 > 解决方案 > js中根据用户输入搜索单词

问题描述

所以我有以下设置,用户输入文本,我想看看是否有任何输入的字符与单词匹配。当我输入说时,一切都很好。

const input = 'memb';

但如果做这样的事情。

 const input = 'member has';

然后它返回假。如果它找到匹配的字符,它应该保持真实,成员是匹配的。Member has 也是一个匹配,因为字符 m、e、m、b、e、r 仍然是一个匹配事件,尽管 h、a、s 不匹配任何其他单词。

任何人都知道如果字符匹配,我怎样才能让它继续返回 true ?

const input = 'member has';
const inputLower = input.toLowerCase();
const words = ['member', 'support', 'life'];
const result = words.some(word => {
  const words = word.split(',');
  return words.some(r => r.toLowerCase().includes(inputLower));
});

console.log('result = ', result);

标签: javascript

解决方案


您可以添加反向逻辑,您还可以在其中检查是否inputLower包括r

const input = 'memb has';
let inputLower = input.toLowerCase();
const words = ['member', 'support', 'life'];
const result = words.some(word => {
  const words = word.split(',');
  return words.some(r => {
    if (~inputLower.indexOf( " " )) {
    // only check the first word if there are multiple
      inputLower = inputLower.substring( 0, inputLower.indexOf( " " ) );
    }
    return r.toLowerCase().includes(inputLower) || inputLower.includes(r.toLowerCase());
  });
});

console.log('result = ', result);


推荐阅读