DEV Community

Cover image for Highlight Text in React Native [but with a twist]
Oluwaseyi Komolafe
Oluwaseyi Komolafe

Posted on

1

Highlight Text in React Native [but with a twist]

Now i came across this issue and i thought it something i should share after getting past it.

A little back story

So, i am working on a chat platform using react native and i have to integrate the search in chat logic but the twist to it is that the text i am searching through is in an HTML form which makes it require a different approach.

So now you get the point, let's go straight to the code.

...
  const {width} = useWindowDimensions();
  const escapeRegExp = (text: string) => {
    return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
  const replaceAll = (str: string, match: string, replacement: any) => {
    if (str === undefined || str === null) {
      return '';
    }
    return str.replace(new RegExp(escapeRegExp(match), 'g'), () => replacement);
  };
  let txt = replaceAll(textProps?.text, '\n\n', '<br><br>');
  txt = replaceAll(textProps?.text, '\n', '<br>');

  const highlightedText = txt
    .replace(
      new RegExp(textProps?.searchedWord, 'gi'),
      `<span style="background-color: #FF842D;">${textProps?.searchedWord}</span>`,
    );

...
  return (
  <View>
    <HTML
          contentWidth={width}
          source={{html: `<div style="color:white;">${highlightedText}</div>`}}
        />
    </View>
  );
};

...
Enter fullscreen mode Exit fullscreen mode

So the escapeRegExp function is replacing all of the characters in text except for letters, numbers, and symbols.

The replaceAll function: The first line checks if str is undefined or null.
If it's not then it continues on to the next line where it performs a search and replace operation on str using escapeRegExp() and new RegExp().

Then we have the highlightedText constant which searches through to get the searched word and replace with a new span with a background color. Which is further put in the HTML tag from the react-native-render-html package. And there you have it. Leave a like if you think this is helpful. Thanks.

Image Screenshot

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay