Liondancer Liondancer - 1 month ago 5x
HTML Question

Wrapping HTML in string form with <span>

I have some HTML represented as a string.


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'>
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

is not splitting my HTML string into the pieces I want -->
"<div class='a'>"


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>");