improve function to highlight all types of search terms – react native Code Answer

I am running a React Native app. I have a SearchBar that highlights the text in the search results.

enter image description here


Code:

Highlight(fullText, searchTerm){   //Highlight function
  if (!searchTerm.trim()) {
    return <Text>{fullText}</Text>
  }
  const regex = new RegExp(`(${_.escapeRegExp(searchTerm)})`, 'gi')
  const parts = fullText.split(regex)
  let final = parts.filter(part => part).map((part, i) => regex.test(part) ?
      <Text style={{backgroundColor: 'coral'}} key={i}>{part}</Text>
     : <Text key={i}>{part}</Text>
  )
  return (
    <Text>{final}</Text>
  )
}






render(){

<Text> this.Hightlight(text, search) </Text>

}


But this Highlight function doesn’t work for the below search term.
I typed “ha mess” but neither “ha” nor “mess” was highlighted.

enter image description here

I want the text to be highlighted even when its not consecutive.
How can i tweak the highlight function to achieve this??

Expected result is something like below. Everything gets highlighted irrespective of the order of words.

enter image description here

Answer

You need to split the searchTerm with spaces.

const regexStr = "(" + searchTerm.trim().split(/s+/).map(escapeRegExp).join("|") + ")";
const regex = new RegExp(regexStr, "gi");

Live demo available at: https://codesandbox.io/s/keen-pascal-4trrk?file=/src/App.js:419-460

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji