0

I've found an useful post here on StackOverflow, I use to hightlight specific text on a website: Link to Answer

I'll post it again (modified):

function hiliter(word) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="highlight">' + word + '</span>';
content.innerHTML = content.innerHTML.replace(rgxp, repl);
}

Now I tried to use this to find something between < and >

hiliter('&lt;(.*)&gt;');

This finds the correct section I want to hightlight, but output changes from e.g. <Example> to <(.*)> on the page.

How do I search with this wildcard, but keep the html from the wildcard search when replacing?

Thanks in advance!

Community
  • 1
  • 1
Fabian
  • 3,465
  • 4
  • 34
  • 42

1 Answers1

3

You can pass a function to .replace [MDN]:

function hiliter(word) {
    var rgxp = new RegExp(word, 'g');
    content.innerHTML = content.innerHTML.replace(rgxp, function(match, word) {
         return '<span class="highlight">' + match + '</span>';
    });
}

word will contain the contents of the first capture group, namely what was matched by .*, match will contains the whole match, i.e. the word including &lt; and &gt;.

A general note: If you use innerHTML, you will destroy and create all the HTML elements. Event handlers bound via JavaScript will be destroyed.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143