如何在JS中用正则实现字符串数组模糊最佳匹配功能
原代码问题排查
你编写的代码存在两个核心问题:
- 字符串类型没有
test()方法,该方法是正则表达式的专属方法,直接调用category.test()会抛出语法错误 - 没有配置大小写不敏感逻辑,也没有实现子串匹配的规则,自然无法命中你期望的部分匹配场景
实现方案
方案1:使用includes()实现(推荐,性能更优)
该方案通过统一转换大小写实现不区分大小写匹配,适合常规的连续子串匹配场景:
const myCategories = ["Alligator", "Rhyno", "Elephant"] const userInput = "eph" const matchResult = myCategories.find(category => // 统一转为小写后判断是否包含用户输入的内容 category.toLowerCase().includes(userInput.toLowerCase()) ) console.log(matchResult) // 输出:Elephant
方案2:使用正则表达式实现
如果后续需要扩展更复杂的匹配规则,可以通过构造正则对象实现:
const myCategories = ["Alligator", "Rhyno", "Elephant"] const userInput = "rho" // 构造大小写不敏感的正则表达式,i标识代表忽略大小写 const matchReg = new RegExp(userInput, 'i') // 注意是正则对象调用test方法,传入待匹配的字符串,顺序和你原代码相反 const matchResult = myCategories.find(category => matchReg.test(category)) console.log(matchResult) // 输出:Rhyno
内容的提问来源于stack exchange,提问作者Cristian Nicolae Perjescu
相关产品推荐
相关产品推荐

