【问题标题】:How do I replace string with HTML DOM replace如何用 HTML DOM 替换字符串
【发布时间】:2021-09-08 16:04:40
【问题描述】:

我的字符串

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

我想把整个 HTML 字符串替换成这样

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

这意味着没有这个额外的“&lt;/div&gt;

我已经尝试过,但不起作用:

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

有人可以推荐我吗?

【问题讨论】:

标签: javascript html regex dom replace


【解决方案1】:

给你;

    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 部分。

【讨论】:

  • 谢谢。不知道有多少空位怎么办?
  • 对不起,我只是按照你的回答回答了,但让我试试。请稍等
【解决方案2】:

你也可以尝试使用jQuery方法.replaceWith而不是.replace

【讨论】:

    【解决方案3】:

    为什么不使用浏览器的宽松解析能力来理解您损坏的 HTML?

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

    就像魔术一样,多余的&lt;/div&gt; 消失了。耶。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 2011-05-02
      相关资源
      最近更新 更多