如何解决自定义突出显示功能不适用于特殊字符 - React Native
我一直在测试我的 React-native 应用程序的前端并发现了一些问题。
有一个 SearchBar 可以突出显示搜索结果中的文本,如下所示。
但是当我尝试搜索 "( )[ ] ! +,. & %" 以及更多字符时,该字符会显示在搜索结果中但未突出显示。我猜这与 RegExp 有关。
escape = function( value ) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$%#\s]/g,"\\$&");
}
getHighlightedText(text){ // Highlight logic
const {value} = this.props;
if(value == "" || value == null || value == 0){
return <Text> {text} </Text>
}
else{
const words = value.split(/\s+/g).filter(word => word.length);
const pattern = words.join('|');
const tex = escape(pattern);
const re = new RegExp(tex,'gi')
const children = [];
let before,highlighted,match,pos = 0;
const matches = text.match(re);
if(matches != null){
for( match of matches ){
match = re.exec(text)
if(pos < match.index) {
before = text.substring(pos,match.index);
if(before.length){
children.push(before)
}
}
highlighted = <Text style={{ backgroundColor: 'coral'}} key={match.index + match[0].length}>{match[0]}</Text>
children.push(highlighted);
pos = match.index + match[0].length;
}
}
if(pos < text.length){
const last = text.substring(pos);
children.push(last);
}
return <Text>{children}</Text>
}
render() {
<Text> {value !== "" ? this.getHighlightedText(text) : text} </Text>
}
我希望突出显示所有字符。
任何建议都可以很好地纠正此问题。
解决方法
您的答案在代码的第一行!
为什么要使用“转义”功能?您在突出显示之前删除代码中的特殊字符
escape = function( value ) {
return value.replace(/[\-\[\]{}()*+?.,\\\^$%#\s]/g,"\\$&");
}
这是一个更干净的版本和更好的代码版本:
const Highlighted = ({text = '',highlight = ''}) => {
if (!highlight.trim()) {
return <Text>{text}</Text>;
}
const regex = new RegExp(`(${_.escapeRegExp(highlight)})`,'gi');
const parts = text.split(regex);
return (
<Text>
{parts
.filter(part => part)
.map((part,i) =>
regex.test(part) ? (
<Text style={{backgroundColor: '#fcf8e3'}} key={i}>
{part}
</Text>
) : (
<Text key={i}>{part}</Text>
),)}
</Text>
);
};
然后
<Highlighted
text={allTextsHere}
highlight={
searchTermHere}
/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。