前言
最近接手的一个项目是react-native 技术栈,有一个需求是搜索文本高亮。刚开始以为和普通的文本高亮的实现方式是一样的,即用正则 + replace,结果在实现的过程中发现不行, replace 之后会变成[Object object]。
实现
正则肯定还是得用,只不过不是用 replace 而是用 split 配合正则使用,会把原字符串转换成数组,再配合 map 就可以实现了。 参考 REG
const myString = "Hello 1 word. Sentence number 2.";
const splits = myString.split(/(\d)/);
console.log(splits);
// [ "Hello ", "1", " word. Sentence number ", "2", "." ]
核心代码如下:
import React, {memo} from 'react';
import styled from '@emotion/native';
const Highlight = styled.Text`
color: green;
`;
export const highlight = (texts = '', keywords = '', style) => {
let parts = texts.split(new RegExp(`(${keywords})`, 'gi'));
return (
<>
{parts.map((part, i) =>
part?.toLowerCase() === keywords?.toLowerCase() ? (
<Highlight key={i} style={style}>
{part}
</Highlight>
) : (
part
),
)}
</>
);
};
总结
这样一个非常简单的react文本高亮就实现了,这个实现只是一个简单的思路,更复杂的可以基于这个做扩展