Highlighting a substring in a string

I'm trying to highlight a matched substring in a searchable array of strings. I'm pretty close I think, just that last bit is not working.

I display an array of strings. When I type in an input the substrings in the array are supposed to get highlighted (using <mark></mark>) when matched with the input. The matching works ok but instead of highlighted text I get [object Object] instead. So this is the part of code in question (it sits in Jsx inside a .map() method:

  {item.matched.length > 0
    ? item.name.replace(new RegExp(inputText, 'gi'), (match) => (
    : item.name}

The item is an element of the array that I'm mapping and has two properties: name & matched. matched is either empty or contains the typed search pattern if part or all of name matches it. And this is what I'm getting when typing into text box:

enter image description here

So clearly the search and match work correctly and look what I get: [object Object] instead of highlighted search pattern. I've tried to return a template string, like that backquote<mark>${match}</mark>backquote, but that results in displaying <mark>a</mark> in my example.

So I'm at loss here and any constructive feedback will be greatly appreciated.

1 answer

  • answered 2021-11-23 02:57 Mahesh K S

    we should render at in html

    <div dangerouslySetInnerHTML={{ __html: (item.matched.length > 0
        ? item.name.replace(new RegExp(inputText, 'gi'), (match) => {
            return `<span>${match}</span>`
        : item.name) }}>

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum