RegExp wildcard shouldn't overwrite
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('<(.*)>');
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!
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 <
and >
.
A general note: If you use innerHTML
, you will destroy and create all the HTML elements. Event handlers bound via JavaScript will be destroyed.
精彩评论