javascript - 如何用 HTML DOM 替换替换字符串

标签 javascript html regex dom replace

我的字符串

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/

相关文章:

php - 数据库行中的YouTube ID

javascript - 设置单选按钮在单击文本区域时选中

javascript - 使用 Angular Material 上传文件

html - 第二列的高度

javascript - 如何找到网站的哪一部分导致浏览器内存泄漏?

html - 如何使用 CSS flexbox 正确对齐按钮

regex - 匹配所有内容直到大写单词

objective-c - 在 xcode 中用 "{"替换 "(newline){"的正则表达式

javascript - 使时钟自动刷新

javascript - Angular : Why is my watch not firing?