JavaScript如何实现对象数组内的部分子字符串模糊匹配
问题描述
原有代码仅支持匹配完整单词"gorilla",需要调整实现任意位置的部分子串匹配能力,支持匹配"gor"、"illa"、"orill"这类片段,效果等价于MySQL中%关键词%格式的LIKE模糊查询。
原有代码如下:
const jungle = [ { name: "frog", threat: 0 }, { name: "monkey", threat: 5 }, { name: "gorilla", threat: 8 }, { name: "lion", threat: 10 } ]; const names = jungle.map(el => el.name); // 仅能匹配完整值,返回true document.write(names.includes("gorilla"));
实现方法
原逻辑使用数组的includes()方法,该方法只会判断数组中是否存在和传入参数完全相等的元素,无法识别元素内部的子串,因此无法实现模糊匹配效果。
直接使用字符串自带的includes()方法做子串判断即可,该方法本身就是判断当前字符串中是否包含任意位置的指定子串,刚好对应%xxx%的模糊匹配规则。
- 如果只需要判断是否存在匹配项,用
Array.some():
const searchKey = "gor"; // 存在匹配返回true,否则返回false const isMatched = jungle.some(item => item.name.includes(searchKey)); document.write(isMatched); // 输出true
- 如果需要拿到所有符合匹配规则的条目,用
Array.filter():
const searchKey = "illa"; // 返回所有name字段包含搜索关键词的条目组成的数组 const matchedItems = jungle.filter(item => item.name.includes(searchKey)); console.log(matchedItems); // 输出 [{ name: "gorilla", threat: 8 }]
如果需要实现不区分大小写的模糊匹配,只需要在判断前统一把字段值和搜索关键词转为小写(或大写)即可:
const searchKey = "GOR"; const isMatched = jungle.some(item => item.name.toLowerCase().includes(searchKey.toLowerCase()));
内容的提问来源于stack exchange,提问作者Ruy Hoffmann
相关产品推荐
相关产品推荐

