I am building an autocomplete in JavaScript that needs to highlight words when doing a search:
That works fine, but there's an issue with escaped characters.
When trying to highlight a text with escaped characters (for example regex &>< example
), the following is happening:
That's happening because I am doing the following:
element.innerHTML.replace(/a/g, highlight)
function highlight(str) {
return '<span class="foo"' + '>' + str + '</span>';
}
and innerHTML
includes the word &
, so it makes sense.
In conclusion, I need a way to solve that so I would like a function that:
- receives
a
andregex <br> example
and returnsregex <br> ex<span class="foo">a</span>mple
- receives
r
andregex <br> example
and returns<span class="foo">r</span>egex <b<span class="foo">r</span>> example
- receives
<
andregex <br> example
and returnsregex <span class="foo"><</span>br> example
The entries may or may not contain html blocks, see the issue here (search for <br>
or &
)