用于替换多个 HTML 标签的正则表达式

RegEx for replacing multiple HTML tags

我正在尝试找到一个匹配多个 html 标签的正则表达式,排除中间的内容,以便可以用不同的 html 标签替换包装标签。此替换需要处理大型 HTML 文档,其中有许多相同 <div><strong>...</strong></div> 格式的实例。

当前HTML

<div>
  <div><strong>Heading</strong></div>
  <div>Some other content<div>
  <div><strong>Heading Title 2</strong></div>
  <div>Some more content</div>
</div>

想要HTML

<div>
  <div class="heading">Heading</div>
  <div>Some other content<div>
  <div class="heading">Heading Title 2</div>
  <div>Some more content</div>
</div>

我已经设法找到一个匹配完整字符串的正则表达式,但我不确定如何排除 Heading 内容以及如何最好地替换外部标签。

我目前最好的正则表达式是:/<div><strong\b[^>]*>(.*?)<\/strong><\/div>/g

使用 replaceWith 将 div 替换为新格式的 div。

[...document.querySelectorAll('div > strong')].forEach(item => {
  // item is the 'strong' element
  // Create a new div
  let div = document.createElement('div')

  // Add a heading class to the div
  div.classList.add('heading')

  // Set the text of the div
  div.innerHTML = item.innerHTML
  
  // Replace the 'strong' elements parent with the new div
  item.parentNode.replaceWith(div)
})
.heading {
  font-size: 20px;
  font-weight: bold;
}
<div>
  <div><strong>Heading</strong></div>
  <div>Some other content<div>
  <div><strong>Heading Title 2</strong></div>
  <div>Some more content</div>
</div>

您使用的正则表达式应该有效。您可以使用 </code> 将捕获组复制到结果中。</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre><code>const html = `<div> <div><strong>Heading</strong></div> <div>Some other content<div> <div><strong>Heading Title 2</strong></div> <div>Some more content</div> </div>`; const new_html = html.replace(/<div><strong\b[^>]*>(.*?)<\/strong><\/div>/g, '<div class="heading"></div>'); console.log(new_html);

请注意,如果您尝试更新整个文档的 DOM,这是一种糟糕的方法。替换所有 HTML 将丢弃任何动态状态,例如用户输入、事件侦听器,因为所有 HTML 都是从头开始的 re-parsed。最好使用 DOM 元素方法,如@GetOffMyLawn 的回答。