clauderic/react-native-highlight-words

buf if word start with "+" char

alainib opened this issue ยท 6 comments

hello.

There is a bug if the text to higliht start with a "+"
for example

const display = "+ Laburnocytisus adami" ;

<Highlighter
    highlightStyle={thisstyles.highlighter}
    searchWords={[this.state.valueForModal]}
    textToHighlight={display}
    style={thisstyles.fontSize15}
 />

return this error :

   SyntaxError: SyntaxError: Invalid regular expression: /+/: Nothing to repeat

any idea to fix it ? thx

Tested "+ Laburnocytisus adami" as textToHighlight prop, cannot reproduce.

hello, the problem is when searchWords contain "+"
this is how i get the error :

  this.state.valueForModal = "+ Lab"; // the content is filled from user input searching for string starting with '+ lab'
  const display = "+ Laburnocytisus adami" ;
 
 <Highlighter
                  highlightStyle={thisstyles.highlighter}
                  searchWords={[this.state.valueForModal]}
                  textToHighlight={display}
                  style={thisstyles.fontSize15}
                />

I got that bug when I type "+" or "*" into the search words.
I think you should catch some special characters in Regular expression
For hotfix we can replace the search key before assign to the searchWords like the code bellow:

let searchKey = props.searchKey ? props.searchKey : ""
  const specialKey=["[", "?", "+", "*"]`
  for(i = 0 ; i < specialKey.length; i++ ) {
    searchKey = searchKey.replace(specialKey[i],'\\'+specialKey[i])
  }

I tested with this:

<Highlighter
  style={{ color: '#888', fontSize: 13, fontFamily: 'System', padding: 10 }}
  highlightStyle={{ backgroundColor: '#FEF3A2' }}
  numberOfLines={3}
  ellipsizeMode="middle"
  searchWords={["+ Lab", "* Lab", "? Lab", "[ Lab"]}
  textToHighlight={"+ Laburnocytisus adami"}
  autoEscape={true}
/>

I get:

image

No error, so I still can't reproduce. My env:

React Native 0.57.0

> react-native info

  React Native Environment Info:
    System:
      OS: Windows 10
      CPU: x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
      Memory: 4.65 GB / 15.95 GB
    Binaries:
      Yarn: 1.12.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
      npm: 6.4.1 - C:\Program Files\nodejs\npm.CMD

autoEscape={true} helps to avoid these types of errors if you don't need to process regular expressions, maybe make it true by default?

Yes, it would be nice.