我的字符串
xxx
<div>
test test
</div>
</div>
<h2> Details</h2>
xxx
我想将整个 HTML 字符串替换为类似
xxx
<div>
test test
</div>
<h2> Details</h2>
xxx
这意味着没有这个额外的“</div>
”
我已经尝试过但不起作用:
result = result.replace('</div>\n<h2> Details</h2>', '<h2> Details</h2>');
或使用正则表达式,但“测试测试”也被删除
const excessDiv = /<\/div>(?:.|\n|\r)+?<h2> Details<\/h2>/;
result = result.replace(excessDiv, '</div><h2> Details</h2>');
有人可以推荐我吗?
最佳答案
给你;
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)
重要的部分是我如何编写代码的replace
部分。
关于javascript - 如何用 HTML DOM 替换替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68127975/