I have a string which has html content in it. Something like this
const text = "My name is Alan and I <span>an</span> <div class="someClass">artist</div>."
I render this inside a react component using dangerouslySetInnerHTML
. This text is really long and has different types of HTML tags in it.
I want to search for a word and highlight it in that document as the user is typing. The functionality is similar to the browser's find (cmd + f) feature. As you type the text should get highlighted.
This is what I am looking for:
user types `an`
const text = "My name is Alan and I <span>an</span> <div class="someClass">artist</div>."
result: "My name is Al<mark>an</mark> and I <span><mark>an</mark></span> <div class="someClass">artist</div>."
I tried using this library https://github.com/bvaughn/react-highlight-words but the issue is it highlights the text inside the tags too and messes up the content.
result: "My name is Al<mark>an</mark> and I <sp<mark>an</mark>><mark>an</mark></span> <div class="someClass">artist</div>."
Then I though I'll use my own regex and came up with this regex:
const regex = new RegExp(((`${searchedText}`)(?![^<>]*>)))
but react(eslint) throws this error at ?
:
This experimental syntax requires enabling the parser plugin: 'partial Application'
Here's my code:
get highlightedText() {
if (searchText === '') return self.renderedText;
const regex = new RegExp((`${searchText}`)((?![^<>]*>)));
const parts = self.renderedText.split(regex);
return parts
.map(part => (regex.test(part) ? `<mark>${part}</mark>` : part))
.join('');
},
I am not sure what I am doing wrong. The regex works perfectly fine as I tested the regex using regextester.com
Any help is appreciated. Thanks!