0

I am trying to create a function that takes a query and a result, and returns JSX with the result, but the query is highlighted in bold text. It should ignore special characters and capitalisation.

For example, if you search for Stack it should return 'Stäçkoverflow'. It should also ignore special characters such as spaces, dashes, &, @, %, etc.

So Stack as a query should return 'St-ackoverflow' or 'St ack'overflow.

This is what I have come up so far, it works as long as there are no special characters. But I am having trouble to figure out how to do this with special characters included.

function highlightSearchQuery(searchQuery: string, result: string): JSX.Element {
    const regex = new RegExp(`(${searchQuery})`, 'gi');
    const parts = result.split(regex);
    return (
        <>
            {parts.map((part, index) => {
                const isQueryMatch = part.toLowerCase() === searchQuery.toLowerCase();
                return <Fragment key={index}>{isQueryMatch ? <strong>{part}</strong> : part}</Fragment>;
            })}
        </>
    );
}

Please note that I know how you can remove the special characters and compare, e.g. const isQueryMatch = part.toLowerCase().replace(/([^a-zA-z0-9]+)/g, '') === searchQuery.toLowerCase().replace(/([^a-zA-z0-9]+)/g, '');.

But how do you remove the special characters before the split? And then put them back in the return just as the original?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
SaroGFX
  • 699
  • 6
  • 20

0 Answers0