簡體   English   中英

RegEx用於替換多個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

您使用的regexp應該可以工作。 您可以使用$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); 

請注意,如果您要更新整個文檔的DOM,這是一種不好的方法。 替換所有HTML將丟棄任何動態狀態,例如用戶輸入,事件偵聽器,因為所有HTML都是從頭開始重新解析的。 最好使用DOM元素方法,如@GetOffMyLawn的答案。

使用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