简体   繁体   English

RegEx用于替换多个HTML标签

[英]RegEx for replacing multiple HTML tags

I am trying to find a regex that will match multiple html tags, exclude the content in between so that the wrapping tags can be replaced by a different html tag. 我试图找到一个正则表达式,它将匹配多个html标签,排除两者之间的内容,以便包装标签可以被另一个html标签代替。 This replacement needs to work on a large HTML document where there are many instances of the same <div><strong>...</strong></div> format. 此替换需要在大型HTML文档上工作,该文档中有许多相同<div><strong>...</strong></div>格式的实例。

Current HTML 目前的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>

Desired HTML 所需的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>

I've managed to find a regex that will match the full string but am unsure how to exclude the Heading content and then how to best replace the outer tags. 我设法找到了一个与完整字符串匹配的正则表达式,但是不确定如何排除Heading内容,然后如何最好地替换外部标签。

The best regex I have so far is: /<div><strong\\b[^>]*>(.*?)<\\/strong><\\/div>/g 到目前为止,我最好的正则表达式是:/< /<div><strong\\b[^>]*>(.*?)<\\/strong><\\/div>/g

The regexp you use should work. 您使用的regexp应该可以工作。 You can use $1 to copy the capture group to the result. 您可以使用$1将捕获组复制到结果中。

 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">$1</div>'); console.log(new_html); 

Note that this is a bad approach if you're trying to update the DOM of the entire document. 请注意,如果您要更新整个文档的DOM,这是一种不好的方法。 Replacing all the HTML will discard any dynamic state, such as user inputs, event listeners, since all the HTML is re-parsed from scratch. 替换所有HTML将丢弃任何动态状态,例如用户输入,事件侦听器,因为所有HTML都是从头开始重新解析的。 It's better to use DOM element methods, as in @GetOffMyLawn's answer. 最好使用DOM元素方法,如@GetOffMyLawn的答案。

Use replaceWith to replace the div with a newly formatted div. 使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM