如何使用 javaScript 正则表达式在数组中搜索准确或最接近的单词?

How to search exact or closest word in array, using javaScript RegEx?

在我的应用程序中,我使用正则表达式实现了本地搜索,我遇到了问题,即使经过多次搜索我也找不到解决方案,正如你所看到的,我有 words 数组,我根据条件对其进行过滤,我想实现类似的东西:

if user writes ele into the search box, I want to get ['electric', 'elektric'], same should happen if user writes ric into the input field result: ['electric', 'elektric'], but In case the user enters the exact name, for example electric result should be : ['electric'] At last, if input will be cooling result should be ['engine cooling']

如您所见,我的目标是系统搜索准确的单词或准确的字母或最接近的逻辑选项。我会接受任何建议,thanx

let words = ['electric', 'elektric', 'engine cooling']

function bestMatch(event){
 let match = words.filter((e) => new  RegExp(`^${event.value}`,"ig").test(e));
 console.log(match)
}
<input type="text" placeholder="best match" onchange="bestMatch(this)" />

在前后添加 .* 以使正则表达式起作用,以便在 word 中的位置无关紧要,尽管根据您的要求不需要正则表达式。相反,您可以使用 includes。最后 onkeyup 可能会 better/faster 获得结果

使用正则表达式:

let words = ['electric', 'elektric', 'engine cooling']

function bestMatch(event){
 let match = words.filter((e) => new  RegExp(`^.*${event.value}.*`,"ig").test(e));
 console.log(match)
}
<input type="text" placeholder="best match" onchange="bestMatch(this)" />
没有正则表达式(并使用 onkeyup):
let words = ['electric', 'elektric', 'engine cooling']

function bestMatch(event){
 let match = words.filter((e) => e.includes(event.value.toLowerCase()))
 console.log(match)
}
<input type="text" placeholder="best match" onkeyup="bestMatch(this)" />