最近新写的需求有这么一个小功能,对列表的数据进行过滤(支持多个词,相信大家都会想到使用正则匹配来做
代码如下:
let data = [
{ title: 'Sponsored Amazon' },
{ title: 'Bounty' },
{ title: 'Paperless Kitchen Dish Cloths' },
{ title: 'Centerpull' },
{ title: 'Premium Quality Fits Bounty' },
{ title: 'Shop Glad' },
{ title: 'previously branded Preference' },
{ title: 'Pacific Blue Select' },
{ title: 'Glad paper plates' },
{ title: 'Reusable' }
]
let includesTitle = ['Sponsored', 'Amazon', 'Bounty', 'Reusable']
const a = includesTitle.join('|')
const reg = new RegExp(`(${a})`, 'gi')
function filter(data) {
return data.reduce((pre, cur) => {
if (reg.test(cur.title)) {
pre.push(cur.title)
}
return pre
}, [])
}
console.log(filter(data))
理想输出:
实际输出:
查阅资料后发现,原来正则中还有这么一个属性lastIndex
,它的值是正则下一次匹配时的起始位置
参考链接:循环下的正则匹配?说说正则中的lastIndex
在正则中包含全局标志g时,正则的test和exec方法就会使用到这个属性,具体规则如下:
初始状态下
lastIndex
的值为0
若成功匹配,lastIndex
的值就被更新成被匹配字符串后面的第一个字符的index,或者可理解为被匹配字符串的最后一个字符index + 1
若匹配失败,lastIndex则被重置为0
如果继续使用原先的正则进行下一轮匹配,则会从字符串lastIndex
的位置开始进行
将代码中的全局匹配g
删掉,得到了理想的输出
在此对‘神奇’的正则匹配中的lastIndex
做个浅浅的记录,大家在使用正则的test
和exec
方法,谨慎使用全局标志g
,避免bug
的出现噢~