2

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. What about without knowing how many empty spaces is there?
Sorry i just answered as per your answer but let me try. Please wait a sec
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.