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


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


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:

Related Posts

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