How do I replace string with HTML DOM replace

Viewed 91

My string

xxx
<div>
test test
</div>
</div>
<h2> Details</h2>
xxx

And I would like to replace the whole HTML string to be like

xxx
<div>
test test
</div>
<h2> Details</h2>
xxx

So that means without this extra "</div>"

I try already but doesn't work:

result = result.replace('</div>\n<h2> Details</h2>', '<h2> Details</h2>');

or with regex but then "test test" is also deleted

const excessDiv = /<\/div>(?:.|\n|\r)+?<h2> Details<\/h2>/;
result = result.replace(excessDiv, '</div><h2> Details</h2>');

Can someone please suggest me?

3 Answers

Here you go;

    let htmlStr = `xxx
    <div>
    test test
    </div>
    </div>
    <h2> Details</h2>
    xxx`

    let modStr = htmlStr.replace(`</div>
    <h2> Details</h2>`, "<h2> Details</h2>")

    console.log(modStr)

The important part is how i write the replace part of code.

Also you can try to use jQuery method .replaceWith instead .replace.

Why not use the lenient parsing power of the browser to make sense of your broken HTML?

var el=document.createElement("div")
el.innerHTML=`xxx
<div>
test test
</div>
</div>
<h2> Details</h2>
xxx`

console.log(el.innerHTML)

and like magic, the extra </div> is gone. Yay.

Related