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