簡體   English   中英

使用javascript替換開始和結束的多個html標簽

[英]Replace starting and ending multiple html tags using javascript

我想刪除以下標簽

  1.  <div>
  2.  </div>
  3.  <p>
  4.   </p>
  5.   <span>
  6.   </span>

var str =  '<div><p><span>Hello World</span></p></div>';

我可以

str = str.replace('<div>', '');
str = str.replace('<p>', '');

等等。

但是使用正則表達式等可以一步完成相同的任務。

請勿為此使用正則表達式: RegEx匹配除XHTML自包含標記之外的其他開放標記

解析HTML並檢索您需要的內容。 這是一種基本的方法,可以從您提供的節點中檢索文本。 您可以進一步擴展它以播種您的需求。

 var container = document.createElement("div"); //load div in memory
 container.insertAdjacentHTML("afterbegin", str); //append the nodes into the container div.

 str = container.getElementsByTagName("span")[0].textContent || container.getElementsByTagName;("span")[0].innerText;

您甚至可以做container.textContent || container.innerText container.textContent || container.innerText ; 從字符串容器HTML元素中獲取所有文本且沒有節點。 (innerText在那里支持較舊的瀏覽器IE)。

試試這個模式:

/<\/?([a-z])+\>/g

這是一個例子

RegExr v2.0是用於測試正則表達式的非常方便的工具。 為了查看結果,請單擊頁面底部的“替換”選項卡。

希望這就是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM