【发布时间】:2021-06-30 06:59:05
【问题描述】:
我一直在测试我的 React-native App 的前端并发现了一些问题。
有一个 SearchBar 突出显示搜索结果中的文本,如下所示。
但是当我尝试搜索 "( )[ ] ! + , . & %" 以及更多字符时,该字符会显示在搜索结果中但未突出显示。我猜这与正则表达式有关。
高亮功能代码:
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>
}
我希望突出显示所有字符。
任何建议都会很好地纠正这个问题。
【问题讨论】:
标签: javascript reactjs regex react-native