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

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay