【问题标题】:custom highlight function doesn't work with special characters - React Native自定义突出显示功能不适用于特殊字符 - React Native
【发布时间】: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


    【解决方案1】:

    您的答案在代码的第一行!

    为什么要使用“转义”功能?您在突出显示之前删除了代码中的特殊字符

    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}
            />
    

    【讨论】:

    • 如果我不使用转义函数,那么当我在 SearchBar 中键入“() 或!或 + 或 []”时,它会抛出此错误“SyntaxError: Invalid regular expression: unmatched parentheses”
    • 使用这个:new RegExp((${_.escapeRegExp(highlight)}), 'gi');
    猜你喜欢
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    相关资源
    最近更新 更多