在项目开发过程中遇到日志搜索高亮显示关键字的需求:
本文采用数组方法reduce实现。
reduce简介:
语法
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数:
参数 | 描述 |
---|---|
function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 |
initialValue | 可选。传递给函数的初始值 |
函数参数:
参数 | 描述 |
---|---|
total | 必需。初始值, 或者上一轮计算结束后的返回值。 |
currentValue | 必需。当前元素(值) |
index | 可选。当前元素(值)的索引 |
arr | 可选。当前元素(值)所属的数组对象。 |
注意:如果initialValue不传,函数的total参数会默认为数组的第一个元素(值),index会从1开始
需求实现思路:
通过忽略大小写的搜索关键字把日志文本拆分为一个数组,再利用忽略大小写的正则匹配出原始文本中的符合要求的值(匹配生成为一个数组),再利用reduce把高亮后的匹配出的关键字按顺序插入到原本应该在的位置,成高亮后的日志文本。
实现代码:
const searchKeyword = new RegExp(value,'ig');//value为输入的值,用正则转换成忽略大小
//data为文本内容,用忽略了大小写的搜索关键字把文本内容拆分为数组,再把高亮后的搜索关键字插入数组
data.split(searchKeyword).reduce((prevResult,current_item,index)=>{
//下述的[index-1],根据上述的注意,没有传递初始值,index是从1开始
return (
<span>
<span>{prevResult}</span>
<span className={styles.highLight}>{data.match(searchKeyword)[index-1]}</span>
<span>{current_item}</span>
</span>
)
})