javascript - 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);
解决方案
您可以添加反向逻辑,您还可以在其中检查是否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);
推荐阅读
- python - y 需要 polyfit 错误 1d 或 2d 数组
- javascript - VueJS:将值绑定到组件
- php - 在循环中创建新变量(PHP)?
- r - 如何根据 R 中纵向情况下不同变量的状态对一个变量进行分组?
- iis - 如何防止需要手动重新启动应用程序池的 IIS 错误再次发生?
- xamarin - UWP 在 webviewer 中获取表单返回“about:blank”而不是表单值
- pandas - 通过 pandas 将 csv 导入转换为单独的列
- coldfusion - 如何在 QueryExecute sql 语句中正确转义冒号?
- mysql - 从表中选择所有早于 3 天的条目
- java - IntelliJ 无法识别来自 gradle 项目的某些导入