Liondancer Liondancer - 2 months ago 6
HTML Question

Wrapping HTML in string form with <span>

I have some HTML represented as a string.

ex:

var testHTMLString = "<div class='a'>test content</div>"


I want to be able to use regex and split this HTML string by its tags and wrap the broken up tag pieces with
<span class='red'>
and
</span>
in order to highlight pieces of the HTML string

expected result:

<span class='red'>"<div class='a'>"</span>test content<span class='red'>"</div>"</span>


I can't seem to get the regex correct in my program but in regex testers it seems to work

testHTMLString.split("/<(\/)?div.*?>/g");
is not splitting my HTML string into the pieces I want -->
"<div class='a'>"
and
"</div>"

Answer

You already answered your question. But you forgot to return applied changes:

function highlightTag(pageSource, tag) {
    var re = new RegExp("<(\/)?" + tag + ".*?>", "g");
    newPageSource = pageSource.replace(re, "<span class='red'>" + tag + "</span>");
    return newPageSource;
}

Also that doesn't completely do what you want. This does:

function highlightTag(pageSource, tag) {
    var re = new RegExp("(<\/?" + tag + "[^<>]*>)", "g");
    return pageSource.replace(re, "<span class='red'>\"$1\"</span>");
}
Comments